1

amount is having diff after multiplying with 100

$amt = 33.48;
echo "$amt: ".gettype($amt);
$amount = $amt* 100;
echo "\n$amount: ".gettype($amount);
echo "\n";
$arr = array($amount);
print_r($arr);
echo "\n".json_encode($arr);

output

33.48: double
3348: double
Array
(
    [0] => 3348
)

[3347.9999999999995]

live output

How 3348 became 3347.9999999999995 ?

NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
Nithee
  • 300
  • 1
  • 12
  • Floating point number precision. – Geno Chen Jan 04 '19 at 13:42
  • Use `$amt = 3348`, handle format in the front end. – Geno Chen Jan 04 '19 at 13:42
  • weird it is happening in only php version **7.1 - 7.3**!! it is working fine for Output for **5.2.0 - 7.0.338** https://3v4l.org/fR9pv – NullPoiиteя Jan 04 '19 at 13:46
  • @JayBlanchard irony is, that [question](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) was asked in **Feb 25 '09** and than they fixed that thing in php version **5.2.0 - 7.0.338** and than again broke it in **7.1 - 7.3** this is just funny af – NullPoiиteя Jan 04 '19 at 13:52
  • LOL @NullPoiиteя, I have followed the problem for a while. – Jay Blanchard Jan 04 '19 at 13:54
  • Thank you all for the quick response, but I am using this in a payment api so I can't round it always , please suggest a better method to handle this planing to do like $diff = $amount -intval(amount); if($diff > 0 && $diff < 1){ $amount = round($amount);} – Nithee Jan 04 '19 at 16:16

0 Answers0