2

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?

tom
  • 2,137
  • 2
  • 27
  • 51

1 Answers1

2

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"​​​​​
​​​​​}​​​​​
Ravenscar
  • 2,730
  • 19
  • 18
  • 2
    I would urge caution when using regular expressions or any naive string-replacement technique here; it is not hard for unexpected input to produce bizarre outputs. – jcalz Aug 11 '18 at 02:08
  • 1
    e.g., input: `{"-.-e+0": 0.1}`, output: not JSON – jcalz Aug 11 '18 at 02:21
  • 1
    @jcalz brings up a good point about regex, Rather than just replacing with "$1" I added a replacement function which tests if the output would be a number. Of course as with anything if it's being used in anger then some unit tests would be a good idea. – Ravenscar Aug 11 '18 at 04:10