Set precision for float number in PHP

I get the number from the database, and this number can be either float or int .

I need to set the decimal precision of the number 3 , which makes the number no more than (relative to decimal places) 5.020 or 1518845.756 .

PHP usage

 round($number, $precision) 

I see the problem:

It rounds the number. I need a function to shorten short decimal places without changing their values, which do not seem to match.

+7
source share
4 answers

You can use number_format() to achieve this:

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

This will convert 1518845.756789 to 1518845.757 .

But if you just want to reduce the number of decimal places to 3 and not round , 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 10 3 (it becomes 1518845756.789 ), discards it by an integer, so everything after three decimal places is deleted (becomes 1518845756 ), and then divide the result by 10 3 (becomes 1518845.756 ).

Demo

+13
source

Its sound resembles a floor with decimal places. So you can try something like

 floor($number*1000)/1000 
+9
source

If I understood correctly, you would not want rounding to happen, and you want accuracy to be 3.

So the idea is to use number_format() for precision 4, and then remove the last digit:

 $number = '1518845.756789'; $precision = 3; echo substr(number_format($number, $precision+1, '.', ''), 0, -1); 

The following is displayed:

 1518845.756 

but not:

 1518845.757 

References: number_format() , substr()

+2
source
 $num=5.1239; $testnum=intval($num*1000)/1000; echo $testnum; //return 5.123 
-1
source

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


All Articles