Hi everybody, I have a form input to get a number (it is a price). It can be a decimal like 102,5. I have to compare it with an other decimal for exemple 102,6. How can handle this ? I don't want to use round() cause i get to compare exactly.
+5
A:
You could compare the absolute (i.e., numerical) difference to an "epsilon" (your "tolerance" 1):
$epsilon = 0.01;
$diff = abs(102.5 - 102.6); // .1
if ($diff <= $epsilon) {
// The numbers are equal
} else {
// The numbers are not equal enough!
}
And, a little reading: "What Every Computer Scientist Should Know About Floating-Point Arithmetic" and "Comparing floating point numbers".
Also, you may find the follow SO questions (and answers!) interesting:
- Most effective way for float and double comparison
- What's wrong with using == to compare floats in Java?
1 That's right: You get to decide what makes the two numbers equal. It could be 0.1
(making 1.1
equal to 1.0
), 0.01
(1.02
~ 1.03
) etc.
jensgram
2010-09-14 08:58:42
tx i test and i will be back
Mamadou
2010-09-14 09:05:21
tx ! does not work yet
Mamadou
2010-09-14 10:41:19
@Mamadou Are your numbers valid? What does `var_dump()` print?
jensgram
2010-09-14 11:07:01
+2
A:
Don't store prices as floats, use integers (store cents, not dollars).
stereofrog
2010-09-14 08:59:51
A:
Just make it decimal out of this format
$kinda_decimal = "102,5";
$kinda_decimal = floatval(str_replace(",",".",$kinda_decimal));
and compare it
Col. Shrapnel
2010-09-14 09:09:42
okay ! the probleme is now when i choose the ( point ) it is not taken as a decimal coma ! I hope you understand ( am french))
Mamadou
2010-09-14 10:32:59