EDIT:
It happens when I use json_encode - the float value is actually correct at 22.6, but the extra decimal places is added after using json_encode()
This only happens when using PHP version "alt-php72"
This string works fine:
$str = '22.5';
$float = json_encode(floatval($str));
echo $float; // 22.5
This one doesn't
$str = '22.6';
$float = json_encode(floatval($str));
echo $float; // 22.60000000000000142108547152020037174224853515625
If the user has entered '22.6', how can I get that number as float without the extra decimal places?
I don't know how many decimal places the user will enter, so if the user enters '22.666' it should still return 22.666 as float
I have tried with number_format
, but that returns a string (although it looks correct):
$float = number_format($str, strlen(substr(strrchr($str, '.'), 1))); returns 22.6 as string
The line above formats the string and returns a value with the correct number of decimal places, since I use strlen(substr(strrchr($str, '.'), 1))
which returns the number of decimal places in the string and uses it in number_format
, but unfortunately it's still a string