Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silly, can't figure out php round down :(

Tags:

php

I have small problem and it might be silly somewhere, but still i have it :)

So the problem is:

By doing this

round(615.36*0.10, 2, PHP_ROUND_HALF_DOWN);

I expect outcome to be 61.53, but it's 61.54.

phpVersion = 5.3.2

Could anyone help me to solve this? Thanks.

like image 342
arma Avatar asked Apr 13 '11 10:04

arma


3 Answers

PHP_ROUND_HALF_DOWN will round the half -- i.e. the 0.005 part.

if you have 61.535, using PHP_ROUND_HALF_DOWN will get you 61.53 -- instead of the 61.54 you should have obtained with usual rounding.
Basicall, the .005 half has been rounded down.

But 61.536 is not a half : .006 is more than .005 ; so rounding that value gives 61.54.



In your case, you could multiply the value by 100, use the floor() function, and divide the result by 100 -- I suppose it would 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) 
like image 194
Pascal MARTIN Avatar answered Nov 03 '22 11:11

Pascal MARTIN


If you want to round down, you'll need to use floor(), which doesn't have a means to specify precision, so it has to be worked around, eg. with

function floor_prec($x, $prec) {
   return floor($x*pow(10,$prec))/pow(10,$prec);
}
like image 22
Patrick Georgi Avatar answered Nov 03 '22 12:11

Patrick Georgi


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

like image 1
bertsisterwanda Avatar answered Nov 03 '22 11:11

bertsisterwanda