Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Round() not working properly

Tags:

php

math

I need help. I'm doing this:

round($myvar,2);

And this is the number I'm getting: 9.779999999999999€

With the other variables it works just fine, any idea how to fix this?

like image 659
Pablo Camara Avatar asked Oct 19 '15 22:10

Pablo Camara


People also ask

How do I round to 2 decimal places in PHP?

Example #1 round() examples php echo round(3.4); // 3 echo round(3.5); // 4 echo round(3.6); // 4 echo round(3.6, 0); // 4 echo round(1.95583, 2); // 1.96 echo round(1241757, -3); // 1242000 echo round(5.045, 2); // 5.05 echo round(5.055, 2); // 5.06 ?>

How do I round up in PHP?

The ceil() function rounds a number UP to the nearest integer, if necessary. Tip: To round a number DOWN to the nearest integer, look at the floor() function. Tip: To round a floating-point number, look at the round() function.

What is round () function?

Description. The ROUND function rounds a number to a specified number of digits. For example, if cell A1 contains 23.7825, and you want to round that value to two decimal places, you can use the following formula: =ROUND(A1, 2) The result of this function is 23.78.

How do you round down a number in PHP?

The floor() function rounds a number DOWN to the nearest integer, if necessary, and returns the result. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a floating-point number, look at the round() function.


2 Answers

I did this:

<?php echo round(9.7752,2);?>

And I got: 9.779999999999999

I believe it's something in php.ini as @MarkBaker said.. But, I fixed it by doing:

<?php echo number_format($myvar,2);

And I got exactly what I wanted. Thanks guys for the help!

like image 125
Pablo Camara Avatar answered Nov 15 '22 15:11

Pablo Camara


what problem I encounter is that round(18.203,2) = 18.2 ,then json_encode(...) = 18.199999999 . so I find the solution is json_encode(strval(round(18.203,2))) = 18.2 it works

like image 22
Joyie Avatar answered Nov 15 '22 13:11

Joyie