PHP creates numbers in decimal places

Asked

Viewed 26 times

0

I’m racking my brain here. I move to a variable the value of 130.67. Then subtract any value from it and then subray the rest to leave the variable with value 0 (exact). Then I test if the value is equal to 0. But it gives error, and when I order to display as many houses as possible (53) I see that when I pass the initial value, instead of having 130.000000000000000000000000000000000 I have 130,66999999999998749444785062223672866821289062500000000. That is, PHP automatically passes values to the third decimal places. I have tried to use round($var, 2), but it doesn’t work. I saw that this "creation of values" differs for other numbers.

<?php
$valor1 = 130.67;
$valor2 = $valor1 - 10;
$valor3 = $valor2 - 120.67;
if ($valor3 == 0) {
    print "Valor zerado";
} else {
    print "Erro, há saldo";
}
?>
  • There are several questions and answers here at Sopt talking about the intrinsic inaccuracy of floating point numbers. If you want accuracy then don’t use the float/double data types.

  • Just appeared: Error, there is balance

  • I recommend using double

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.