This question is best posed as a block of code. Basically I need to know why $float2 is being rounded to 1 whenever it is cast to a string with (string) and also need a way to work around this problem. I'm able to cast other floats to a string without any issue, but this one case where rounding is happening is causing major headaches.
$float1 = 0.99999999999999;
$float2 = 0.999999999999999;
$float3 = 0.00000000000001;
$float4 = 0.000000000000001;
echo $str1 = float_to_string($float1);
echo ' type: '.gettype($str1)."\n"; //Echos: 0.99999999999999 type: string
echo $str2 = float_to_string($float2);
echo ' type: '.gettype($str2)."\n"; //Echos: 1 type: string
echo $str3 = float_to_string($float3);
echo ' type: '.gettype($str3)."\n"; //Echos: 0.00000000000001 type: string
echo $str4 = float_to_string($float4);
echo ' type: '.gettype($str4)."\n"; //Echos: 0.000000000000001 type: string
if ($float2 != 1)
{
echo "No rounding done in if clause so this means that (string) is doing the rounding.\n";
}
function float_to_string($float)
{
$parts = explode('E', $float);
if(count($parts) === 2)
{
$exp = abs(end($parts)) + strlen($parts[0]);
$decimal = number_format($float, $exp); //This converts it to a string
echo "Returning with number_format\n";
return rtrim($decimal, '.0');
}
else
{
echo "Returning without number_format\n";
return (string)$float; //Why is this rounding 0.999999999999999 to 1?! I thought only number_format did rounding.
}
}