代码之家  ›  专栏  ›  技术社区  ›  tom

用科学记数法将数字写入JSON,这样它们周围就不会有引号了

  •  0
  • tom  · 技术社区  · 8 年前

    question ).

    <number> 在我的JavaScript(Angular/TypeScript)应用程序中,我将它们转换成科学形式 (42).toExponential()

    问题是 toExponential() 返回一个字符串值,因此在稍后的JSON表示法中 42 会变成 "4.2e+1" 4.2e+1 .

    我怎样才能去掉引号呢?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Ravenscar    8 年前

    可以使用JSON.stringify函数的替换符将所有数字转换为指数,然后使用regex删除引号,例如。

    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;
      }
    })
    

    给予:

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