Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP number_format is rounding?

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.

like image 228
PhpNhh7 Avatar asked May 22 '11 11:05

PhpNhh7


People also ask

What does Number_format do in PHP?

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.

How can I get only 2 decimal places in PHP?

$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?

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.


2 Answers

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);
like image 61
Emil Vikström Avatar answered Oct 12 '22 23:10

Emil Vikström


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)
like image 23
ThaDafinser Avatar answered Oct 12 '22 22:10

ThaDafinser