gpt4 book ai didi

javascript - 以科学记数法将数字写入 JSON,这样它们就不会被引号括起来

转载 作者:行者123 更新时间:2023-12-03 01:20:22 25 4
gpt4 key购买 nike

我必须以科学记数法将 float 存储在 JSON 中(就像 OP 在 question 中所做的那样)。

我必须写入 JSON 的值是 <number>在我的 JavaScript(Angular/TypeScript)应用程序中,我将它们转换为科学形式,如 (42).toExponential() .

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

如何去掉引号?

最佳答案

您可以使用 JSON.stringify 函数的替换器将所有数字转换为指数,然后使用正则表达式稍后去除引号,例如

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"​​​​​
​​​​​}​​​​​

关于javascript - 以科学记数法将数字写入 JSON,这样它们就不会被引号括起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51795735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com