Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with strange rounding of floats in PHP

As we all know, floating point arithmetic is not always completely accurate, but how do you deal with its inconsistencies?

As an example, in PHP 5.2.9: (this doesn't happen in 5.3)

echo round(14.99225, 4);  // 14.9923 
echo round(15.99225, 4);  // 15.9923 
echo round(16.99225, 4);  // 16.9922 ??
echo round(17.99225, 4);  // 17.9922 ??
echo round(25.99225, 4);  // 25.9922 ??
echo round(26.99225, 4);  // 26.9923

How would you work around this?

like image 595
nickf Avatar asked Feb 12 '10 00:02

nickf


People also ask

How can I limit float to 2 decimal places in PHP?

php $num = 67; $number = sprintf('%. 2f', $num); echo "The number upto two decimal places is $number"; ?> Here, we have used %f for a float value.

How do you round to 2 decimal places in PHP?

Parameter Values Specifies a constant to specify the rounding mode: PHP_ROUND_HALF_UP - Default. Rounds number up to precision decimal, when it is half way there. Rounds 1.5 to 2 and -1.5 to -2.

How do you round a floating-point?

The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.


1 Answers

Welcome to IEEE754, enjoy your stay.

Use bc or gmp instead.

like image 184
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 12:10

Ignacio Vazquez-Abrams