2

I am retrieving some values stored as string which have up to 15 decimal places. I need to json_encodeit and pass it on to javascript as numeric value. So I tried (float)$number, but the number gets rounded-off in this approach. How else can I convert it to number without any rounding?

4
  • us1.php.net/manual/en/function.gmp-init.php Commented Oct 2, 2013 at 18:22
  • Can you post some sample code that demonstrates this? Commented Oct 2, 2013 at 18:22
  • @JohnConde well, I can: print_r(json_decode('{ "test": 3.1234567890123456789 }')); or echo json_encode([ 'test' => 3.1234567890123456789 ]); Commented Oct 2, 2013 at 18:27
  • 1
    @JohnConde Yep Commented Oct 2, 2013 at 18:27

2 Answers 2

3

You should use the GMP library in PHP whenever number precision is important. You may have to enable it inside of your php.ini settings. Search for...

;extension=php_gmp.dll

and change it to

extension=php_gmp.dll

and then you'll be able to use the GMP objects.

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to preserve those decimals: don't parse it. Any number converted to float is subject to precision loss. Can't you just print the variable as received in JS?

5 Comments

My problem is, the other coder doing the js, asked me to provide the output as numeric not a string, which it is by default. I also tried double, but....
True, but then again that means there is no native way of doing this! sigh!
@Bluemagica Not natively. Do you need to do calculations with it?
@Bluemagica Output it as a string. The javascript doesn't need to know: echo "var foo = " . $num_as_string . ";"; - the only time you need to actually do the conversion is if you manipulate the number inside the PHP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.