0

I'm encoding a JSON file with the following function:

json_encode( $config, JSON_PRETTY_PRINT | JSON_FORCE_OBJECT | 
JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK );

The issue is (or I'm pretty sure is) the JSON_NUMERIC_CHECK flag, is causing floats of 5 decimal places or more to be output like this:

1.0e-7

rather than this:

0.0000001

How can I keep my float values intact when outputting the file?

Very weird behavior as floats with shorter decimal places are being encoded just fine.

  • What's wrong with that? It's valid JSON and it represents the same value. – Barmar May 22 '18 at 19:26
  • The software I'm generating the configuration file for is parsing the value as a string - I.E 1.07 – Glenn Bennett May 22 '18 at 19:30
  • 1
    That's a bug in the parser, it should follow the JSON specification. See https://stackoverflow.com/questions/19554972/json-standard-floating-point-numbers?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Barmar May 22 '18 at 19:32
  • 1
    This is why you shouldn't roll your own JSON formatter or parser, it's easy to miss some cases. Use an existing library. – Barmar May 22 '18 at 19:33
  • It's not my software. – Glenn Bennett May 22 '18 at 19:34
  • Well, it's wrong, and I don't think `json_encode()` has a workaround. I guess you could write a regular expression that looks for them and replaces it. – Barmar May 22 '18 at 19:44
  • Aye I was hoping to avoid re-parsing the file to replace them with floating point values, but it looks like it's the only way. – Glenn Bennett May 23 '18 at 14:45

0 Answers0