1

I have a Float variable

$float = 37.80

Then I multiply the float by 100:

$mul = $float *100

Now I have 3780.

$typecasting = (int) $mul;

Now when I print $typecasting, it shows 3779

For example:

$float = 37.80;
$mul = $float*100;
echo $mul;
echo '<br>';
//$mul = 3780
$typecasting = (int) $mul;
echo $typecasting;
// $typecasting shows 3779

I can't understand, how it works. This problem occurs only for 32.80, 33.80, ...4.80. and also for multiples of 2, i.e. 65.60.

yaakov
  • 4,568
  • 4
  • 27
  • 51
sathya seelan
  • 184
  • 10
  • 2
    Floating points aren't perfect in any programming language. You found an example that shows this. https://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples . This happens because binary isn't perfect for storing halves, eights, sixteenths, etc. Just as you can't write 1/3 in the decimal system properly, you can't store `37.80` in binary properly. – Loek Dec 21 '18 at 13:13

1 Answers1

1

Just use floatval() http://php.net/manual/en/function.floatval.php

$float = 37.80;
$mul = $float*100;
echo $mul;
echo '<br>';
//$mul = 3780
$typecasting = floatval($mul);
echo $typecasting;
// $typecasting shows 3779
Ingus
  • 1,026
  • 12
  • 34