Default Number of Decimal Places to Output in PHP

倖福魔咒の 提交于 2019-11-29 08:39:05

And when you can't rely on the PHP configuration, don't forget about number_format() which you can use to define how a number is returned, ex:

// displays 3.14 as 3 and 4.00 as 4    
print number_format($price, 0); 
// display 4 as 4.00 and 1234.56 as 1,234.56 aka money style
print number_format($int, 2, ".", ","); 

PS: and try to avoid using money_format(), as it won't work on Windows and some other boxes

A quick look through the available INI settings makes me thing your precision values are different?

thanks for all the answers - the solution was to cast the return value of the method responsible to a float. I.e. it was doing

return someNumber.' grams';

I just changed it to

return (float)someNumber.' grams';

then PHP truncated any trailing zeroes when required.

Can someone close this?

Just to rule out other possible causes: Where are the numbers coming from? Does it do this with literal values?

It doesn't seem likely that the precision setting alone could cause this. Check also if anything might be interfering with the output via things like auto_prepend_file or output_handler.

You should use the round() command to always round down the precision you want, otherwise some day you'll get something like 2.2000000000123 due to the nature of float arithmetic.

Somnath Muluk

Try the built in function round;

float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] );

Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

Example #1 round() examples

<?php
echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06
?>

Example #2 mode examples

<?php
echo round(9.5, 0, PHP_ROUND_HALF_UP);   // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD);  // 9

echo round(8.5, 0, PHP_ROUND_HALF_UP);   // 9
echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_ODD);  // 9
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!