gpt4 book ai didi

javascript - 使用 SI 单位将数字格式化为三个 sig figs

转载 作者:行者123 更新时间:2023-11-29 22:46:10 25 4
gpt4 key购买 nike

我想使用 SI 单位将整数格式化为 3 位有效数字。例如:

1     => '1'
999 => '999'
1234 => '1.23k'
1235 => '1.24k'

下面是我所拥有的一个功能的粗略破解,但仍然不能满足我所有的测试。我遇到的问题涉及检测何时 9... 会四舍五入到 10...,因此末尾需要少一位小数。

tests = [[9,'9'],[1,'1'],[10,'10'],[99,'99'],[100,'100'],[999,'999'],
[1000,'1.00k'],[1004,'1.00k'],[1009,'1.01k'],[1472,'1.47k'],
[1926,'1.93k'],[1999,'2.00k'],[2000,'2.00k'],[9813,'9.81k'],
[9990,'9.99k'],[9999,'10.0k'],[10000,'10.0k'],[10010,'10.0k'],
[60712,'60.7k'],[98712,'98.7k'],[99949,'99.9k'],[99950,'100k'],
[99999,'100k'],[100000,'100k'],[400499,'400k'],[999499,'999k'],
[999500,'1.00M'],[999999,'1.00M'],[1000000,'1.00M'],
[1234567,'1.23M'],[12345678,'12.3M'],[123456789,'123M']]

tests.forEach( ([n,expected]) => {
const actual = siRound(n)
console.log(n, actual, actual==expected ? '=' : '≠', expected)
})

function siRound(x) {
if (x<1e3) return x+'';
const digits = Math.log10(x) | 0
const tier = digits/3 | 0
let str = (x / 10**(tier*3)).toFixed(2-(digits%3))
// Turn "10.00" into "10.0" and "100.0" into "100"
str = str.replace(/^(.{3})\..+|^(.{4}).+/, '$1$2')
return str + (['','k','M','G','T'])[tier]
}

最佳答案

让你的方法像递归一样。添加这个,返回前检查:

if (str.length>4) { 
siRound(str)
}

tests = [[9,'9'],[1,'1'],[10,'10'],[99,'99'],[100,'100'],[999,'999'],
[1000,'1.00k'],[1004,'1.00k'],[1009,'1.01k'],[1472,'1.47k'],
[1926,'1.93k'],[1999,'2.00k'],[2000,'2.00k'],[9813,'9.81k'],
[9990,'9.99k'],[9999,'10.0k'],[10000,'10.0k'],[10010,'10.0k'],
[60712,'60.7k'],[98712,'98.7k'],[99949,'99.9k'],[99950,'100k'],
[99999,'100k'],[100000,'100k'],[400499,'400k'],[999499,'999k'],
[999500,'1.00M'],[999999,'1.00M'],[1000000,'1.00M'],
[1234567,'1.23M'],[12345678,'12.3M'],[123456789,'123M']]

tests.forEach( ([n,expected]) => {
const actual = siRound(n)
console.log(n, actual, actual==expected ? '=' : '≠', expected)
})

function siRound(x) {
if (x<1e3) return x+'';
const digits = Math.log10(x) | 0
const tier = digits/3 | 0
let str = (x / 10**(tier*3)).toFixed(2-(digits%3))
// Turn "10.00" into "10.0" and "100.0" into "100"
str = str.replace(/^(.{3})\..+|^(.{4}).+/, '$1$2')
if (str.length>4) { ///Add this check
siRound(str)
}
return str + (['','k','M','G','T'])[tier]
}

关于javascript - 使用 SI 单位将数字格式化为三个 sig figs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58506569/

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