简体   繁体   中英

2 digit precision PHP

I am trying to do a 2 digit precision in PHP Laravel project but it doesnt work. I have the value 1234666.6666667 that I want to make 1234666.66 but all the results I've seen in here or/and in other search pages. This is my code:

$value = 1234666.6666667;
return round($value,2);

any other solution?

EDIT:

As I see, you actually want to floor number to 2 decimal points, not to round it, so this answer could help you:

$value = 1234666.6666667;
floor($value * 100) / 100; // returns 1234666.66

If you want 3 decimal points you need to multiple and divide with 1000, for 4 - with 10000 and etc.

You can use number_format , it convert value to string though, so you lose real float value:

 
 
 
  
  $value = 1234666.6666667; echo number_format($value, 2, '.', ''); // prints 1234666.67
 
  

Use this function.

function truncate($i) {
    return floor($i*100) / 100.0;
}

Then you can do

$value = truncate(123.5666666); // 123.56

A pragmatic way is to use round($value - 0.05, 2) , but even that gets you into hot water with some edge cases. Floating point numbers just don't round well. It's life I'm afraid. The closest double to 1234666.66 is

1234666.65999999991618096828460693359375

That's what $value will be after applying my formula! Really, if you want exact decimal precision, then you need to use a decimal type. Else use integer types and work in multiples of 100.

For the former choice, see http://de2.php.net/manual/en/ref.bc.php

  $value = bcadd($value, 0, 2); // 1234666.6666667 -> 1234666.66

解决此问题的另一种更奇特的方法是使用bcadd(),其$ right_operand的虚拟值为0,这将为您提供十进制后的2个数字。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM