Search code examples
javascriptjsontypescripttype-conversionstringify

Writing numbers to JSON in scientific notation so that they don't get quotation marks around them


I have to store floating point numbers in JSON in scientific notation (just like the OP does in this question).

The values I have to write into JSON are <number>s in my JavaScript (Angular/TypeScript) application, and I'm converting them into scientific form like (42).toExponential().

The problem is that toExponential() returns a string value, so later in my JSON notation 42 will become "4.2e+1" and not 4.2e+1.

How could I get rid of the quotation marks?


Solution

  • You could use a replacer for the JSON.stringify function to convert all numbers to exponential, then use a regex to strip the quotes later, e.g.

    const struct = { foo : 1000000000000000000000000, bar: 12345, baz : "hello", boop : 0.1, bad: "-.e-0"};
    
    const replacer = (key, val) => {
      if (typeof val === 'number') {
        return val.toExponential();
      }
      return val;
    }
    
    let res = JSON.stringify(struct, replacer, 2)
    
    res = res.replace(/"([-0-9.]+e[-+][0-9]+)"/g, (input, output) => {
      try {
        return isNaN(+output) ? input : output;
      } catch (err) {
        return input;
      }
    })
    

    gives:

    {​​​​​
    ​​​​​  "foo": 1e+24,​​​​​
    ​​​​​  "bar": 1.2345e+4,​​​​​
    ​​​​​  "baz": "hello",​​​​​
    ​​​​​  "boop": 1e-1,​​​​​
    ​​​​​  "bad": "-.e-0"​​​​​
    ​​​​​}​​​​​