I’m facing a very odd phenomenon when trying to separate the whole numbers and decimals from a float value.
<?php
echo "<br>" . numToWords(1004712896.17);
function numToWords($value) : String
{
// $words is used to store the translated string
$words = "";
print "<br>VALUE: $value";
$whole = floor($value);
print "<br>WHOLE: $whole";
$deci = $value - $whole;
print "<br>DECI: $deci";
// continue to translate numbers into words
...
return $words;
}
The out put shows the decimal part having some extra numbers attached at the end:
VALUE: 1004712896.17
WHOLE: 1004712896
DECI: 0.16999995708466001004712896
I noticed that the last 12 numbers are the whole-number part of my value. Also, it is not 0.17 as what I entered, but is 0.1699999…
I can get back 17 if I multiply it by 100 and ceil() the result, but still, the extra numbers are present in my result:
$deci = ceil(($value - $whole) * 100);
the output:
DECI: 17001004712896
So… What have I done wrong? I don’t think memory corruption is the cause as I tried to close the tab and re-open it, and even closed my browser and re-open it, the problem persists. And memory overflow is not the problem, since nothing changed even after I’ve reduced the value to the range of thousands.
Is there something I must do before performing any calculation to prevent this, or is this a bug of PHP?
Using XAMPP Version 8.0.30 on FireFox (Latest).
Edit:
trying another method, by using the string equivalent of the value, and then locate the position of the period, and separate the 2 parts into 2 strings, still, the extra numbers are attached to the substring, even when I specifically said I only want 2 characters for my decimal string:
$valstr = strval($value);
print "<br>VALSTR: $valstr";
$pos = strpos($valstr, ".", 0);
$intstr = substr($valstr, 0, $pos);
$decstr = substr($valstr, $pos+1, 2);
print "<br>POS: $pos";
print "<br>IntStr: $intstr";
print "<br>DecStr: $decstr";
output:
VALSTR: 8712896.34
POS: 7
IntStr: 8712896
DecStr: 34008712896 // supposed to be 34 only
I’m starting to think this is a bug in PHP…