Stupid, I can not understand php round down :(

I have a little problem and it might be stupid somewhere, but still I have it :)

So the problem is this:

By doing it

round(615.36*0.10, 2, PHP_ROUND_HALF_DOWN); 

I expect the result to be 61.53 , but it is 61.54 .

 phpVersion = 5.3.2 

Can someone help me solve this problem? Thanks.

+6
source share
3 answers

PHP_ROUND_HALF_DOWN will cover half , i.e. part 0.005 .

if you have 61.535 , when using PHP_ROUND_HALF_DOWN you will get 61.53 - instead of 61.54 , which you should get with normal rounding.
Basicall, .005 half rounded down.

But 61.536 not half : .006 more than .005 ; therefore, rounding this value gives 61.54 .



In your case, you can multiply the value by 100, use the floor () function and divide the result by 100 - I suppose this will give you what you expect:

 $value = 61.536; $value_times_100 = $value * 100; $value_times_100_floored = floor($value_times_100); $value_floored = $value_times_100_floored / 100; var_dump($value_floored); 

Gives me:

 float(61.53) 
+11
source

If you want to round, you will need to use floor (), which does not have the means to indicate accuracy, so you need to handle it, for example. from

 function floor_prec($x, $prec) { return floor($x*pow(10,$prec))/pow(10,$prec); } 
+2
source

you obviously want it to be two decimal places, why not just number_format (615.36 * 0.10, 2)

+1
source

Source: https://habr.com/ru/post/885808/


All Articles