我正在寻找一些算法来“智能”舍入小数字。例如:
让我们有一个具有值的数组:0:4.0236180709235
1:4.02462309509067
2:4.02412058061092
.
.
17: 4.01599998414516
18: 4.01599998414516
19: 4.01949998319149
如果我查看这个数组,我可以确定这个数字在 .000 位置上大多不同,所以它应该返回 -> 3(然后我在 => .toFixed(3) 中使用)
可能我应该计算数组的最大值和最小值之间的差异,并从中获得小数位的最佳数字。
或循环该数组...
第二个例子:0:4.0236180709235
1:4.01462309509067
2:4.03412058061092
.
.
17: 4.05599998414516
18: 4.06599998414516
19: 4.09949998319149
在那里我可以看到round的十进制数应该是2。
谢谢!
最佳答案
您可以取最大值和最小值的增量,并通过取 10 的对数在开始时获得零的计数。然后得到一个正整数作为固定数字的值。
function round(array) {
var min = Math.min(...array),
max = Math.max(...array),
fixed = Math.ceil(-Math.log10(max - min));
if (fixed < 0) return array;
return array.map(v => v.toFixed(fixed));
}
console.log(...round([4.0236180709235, 4.01949998319149]));
console.log(...round([4.0236180709235, 4.09949998319149]))
console.log(...round([100, 20000]));
关于javascript - JS 智能舍入小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60435168/