Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set precision for a float number in PHP

I get a number from database and this number might be either float or int.

I need to set the decimal precision of the number to 3, which makes the number not longer than (regarding decimals) 5.020 or 1518845.756.

Using PHP

round($number, $precision)

I see a problem:

It rounds the number. I need a function to only cut the decimals short, without changing their values which round( ) seems not to follow.

like image 568
Mostafa Talebi Avatar asked Nov 09 '13 11:11

Mostafa Talebi


People also ask

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

What's the correct way to round a PHP string to two decimal places? $number = "520"; // It's a string from a database $formatted_number = round_to_2dp($number); echo $formatted_number; The output should be 520.00 ; How should the round_to_2dp() function definition be?

What is precision PHP?

Description ¶ round(int|float $num , int $precision = 0, int $mode = PHP_ROUND_HALF_UP ): float. Returns the rounded value of num to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).


1 Answers

You can use number_format() to achieve this:

echo number_format((float) $number, $precision, '.', ''); 

This would convert 1518845.756789 to 1518845.757.

But if you just want to cut off the number of decimal places short to 3, and not round, then you can do the following:

$number = intval($number * ($p = pow(10, $precision))) / $p;

It may look intimidating at first, but the concept is really simple. You have a number, you multiply it by 103 (it becomes 1518845756.789), cast it to an integer so everything after the 3 decimal places is removed (becomes 1518845756), and then divide the result by 103 (becomes 1518845.756).

Demo

like image 71
Amal Murali Avatar answered Sep 18 '22 08:09

Amal Murali