Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP dropping decimals without rounding up

I want to drop off decimals without rounding up. For example if I have 1.505, I want to drop last decimal and value should be 1.50. Is there such a function in PHP?

like image 863
newbie Avatar asked Jan 31 '12 11:01

newbie


People also ask

How do I limit decimal places in PHP?

echo(round(-4.40) . "<br>"); echo(round(-4.60));

Does PHP Number_format round?

The PHP number_format() function is used for formatting numbers with decimal places and thousands separators, but it also rounds numbers if there are more decimal places in the original number than required. As with round() it will round up on 5 and down on < 5.


3 Answers

You need floor() in this way:

$rounded = floor($float*100)/100; 

Or you cast to integer:

$rounded = 0.01 * (int)($float*100); 

This way it will not be rounding up.

like image 74
Rene Pot Avatar answered Sep 23 '22 16:09

Rene Pot


Use the PHP native function bcdiv

echo bcdiv(2.56789, 1, 2);  // 2.56
like image 23
paovivi Avatar answered Sep 23 '22 16:09

paovivi


$float = 1.505;

echo sprintf("%.2f", $float);

//outputs 1.50
like image 37
IsisCode Avatar answered Sep 25 '22 16:09

IsisCode