0

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

VirtusB
  • 59
  • 10
  • I can seem to replicate this, what php version are you using? – GTBebbo Apr 18 '20 at 16:32
  • You can't have it both ways unfortunately. A floating point variable can't (reliably) be truncated to a set number of decimal places and still be stored as a float. If you want the value to be formatted to a set number of digits, then you'll need to deal with strings. Why is that a problem? – iainn Apr 18 '20 at 16:33
  • Sorry, I meant to say I **can't** seem to replicate this. [Here's your code](http://sandbox.onlinephpfunctions.com/code/788822b91c077a86e8f116ec2ac69d33170457cc) working on an online php tester – GTBebbo Apr 18 '20 at 16:41
  • @GTBebbo - You're right, I just tested it more and it happens when I use json_encode(floatval("22.6")); It doesn't happen in the PHP sandbox, I'm using alt-php72 from CloudLinux – VirtusB Apr 18 '20 at 16:52

0 Answers0