简体   繁体   中英

PHP rounding my numbers?

I'm doing an API call which is being outputted in JSON ,

The product field is "ProductID":3468490060026049912

I convert to PHP, json_decode()

Then I output the "Product ID" = float(3.4684900600261E+18)

It gets changed to a float which is rounded, I input this figure into MYSQL and it stays as the rounded figure.

How do I convert from JSON to PHP without it rounding, I need it correct to 19 digits?

You can use the JSON_BIGINT_AS_STRING flag int he $options parameter of json_decode . You will have a string, though.

You probably don't need to store these IDs as integers; it's not like you're going to do any maths on them.

Store them as strings, and you won't have any issues with precision, no matter how many digits they are.

The only reason you'd need to store these as integers is if you're using them as your primary ID field in the database and its doing auto-increment for new records.

This is also the correct way to handle storage for phone numbers, zip codes, and other data that is formatted as a number but is actually just an arbitrary sequence.

The value is too big to be stored as an integer on 32 bit machines (the maximum is about 2*10 9 ), that's why PHP converts it to float.

On 64 bit machines PHP can be stored as integer but its value is really close to the limit (which is about 9*10 18 ). Another ID that starts with 9 or is one digit longer doesn't fit and is converted by PHP to float.

But floating point numbers loose the least significant digits.

As a quick workaround you can pass JSON_BIGINT_AS_STRING as the fourth parameter to json_decode() but it doesn't fixes the source of the problem. You can encounter the same problem on the Javascript or the database code.

You better make "ProductID" a string everywhere. It is an identifier, anyway. You don't need to do math operations with it, just to store it and search for it.

Fixed with setting ini_set('precision',19); at the top.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM