Zaokrąglanie ceny brutto bazując na cenie netto i podatku

Zaokrąglanie float'ów w PHP to łatwizna ale czasem potrzeba nam czegoś więcej.  Kiedy mamy w sklepie cenę netto i wartość VAT i na tej podstawie chcemy wygenerować fajną cenę brutto w stylu 123.45 -> 159.90 zamiast: 151.84.

Nic skomplikowanego ale może się komuś przyda prosta funkcja która załatwia sprawę:

function roundPrice($priceWithoutTax, $taxRate = 1, $roundStyle = 1)
{
	$taxMultipler = ($taxRate+100)/100;
	$priceWithTax = $priceWithoutTax*$taxMultipler;
	$priceRounded = ceil($priceWithTax);

	switch ($roundStyle) {
		// xx.99
		case 1:
			$min = (($priceRounded-0.01)-$priceWithTax)/$taxMultipler;
			break;
		// xx.00
		case 2:
			$min = (($priceRounded)-$priceWithTax)/$taxMultipler;
			break;
		// x0.00
		case 3:
			$priceRounded = ceil($priceWithTax/10)*10;
			$min = (($priceRounded)-$priceWithTax)/$taxMultipler;
			break;
		// x9.90
		case 4:
			$priceRounded = ceil($priceWithTax/10)*10;
			$min = (($priceRounded-0.1)-$priceWithTax)/$taxMultipler;
			break;
		default:
			throw new Exception('Invalid round style.');
			break;
	}

	return $priceWithoutTax+$min;
}

Funkcja dla ceny 123.45 i podatku 23%, i styli 1, 2, 3, 4 zwróci nam:

float 151.99
float 152
float 160
float 159.9

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *