I have a price "0,10" or "00000,10"
Now when i try
number_format($price, 2, ',', '')
I get 0,00. How can i fix this? I want 0,10 $. I don't want rounding.
Or when i have 5,678, i get 5,68. But i want 5,67.
PHP | number_format() Function The number_format() function is an inbuilt function in PHP which is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure.
$twoDecNum = sprintf('%0.2f', round($number, 2)); The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding. Save this answer.
How can I get whole number in PHP? The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a number DOWN to the nearest integer, look at the floor() function.
You can increase the size of the number before rounding down with floor:
$price = floor($price * 100) / 100;
$formatted = number_format($price, 2, ',', '');
Another solution, which may give better precision since it avoids floating-point arithmetic, is to format it with three decimals and throw away the last digit after formatting:
$formatted = substr(number_format($price, 3, ',', ''), 0, -1);
Use this (needs activated intl PHP extension)
$numberFmtCurrency = new NumberFormatter('de_AT', NumberFormatter::CURRENCY);
$numberFmtCurrency->setAttribute(NumberFormatter::ROUNDING_INCREMENT, 0);
$numberFmtCurrency->formatCurrency(328.13, 'EUR'); // prints € 328.13 (and not 328.15)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With