简体   繁体   English

JS智能四舍五入小数

[英]JS smart rounding small numbers

I'm looking for some algorithm to "smart" round small numbers.我正在寻找一些算法来“智能”舍入小数。 For example:例如:
Let's have array with values:让我们有一个带值的数组:
0: 4.0236180709235 0: 4.0236180709235
1: 4.02462309509067 1:4.02462309509067
2: 4.02412058061092 2:4.02412058061092
. .
. .
17: 4.01599998414516 17: 4.01599998414516
18: 4.01599998414516 18: 4.01599998414516
19: 4.01949998319149 19: 4.01949998319149

And if I look at this array i can se that this numbers are mostly different in .000 position so it should return -> 3 (that I then use in => .toFixed(3))如果我查看这个数组,我可以看到这些数字在 .000 位置上大部分不同,因此它应该返回 -> 3(然后我在 => .toFixed(3) 中使用)

Probably I should calc the difference between max and min value of array and from that get that best number for decimal places.可能我应该计算数组的最大值和最小值之间的差异,并从中获得小数位的最佳数字。

Or loop that array...或循环该数组...

Second example:第二个例子:
0: 4.0236180709235 0: 4.0236180709235
1: 4.01462309509067 1:4.01462309509067
2: 4.03412058061092 2:4.03412058061092
. .
. .
17: 4.05599998414516 17: 4.05599998414516
18: 4.06599998414516 18: 4.06599998414516
19: 4.09949998319149 19: 4.09949998319149
There I can see that decimal number for round should be 2.在那里我可以看到圆形的十进制数应该是 2。

Thanks!谢谢!

You could take the delta of max and min value and get the count of zeros at start by taking the logarithm of 10. Then get a positive rounded up integer as value for fixing the number.您可以取最大值和最小值的增量,并通过取 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]));

Sorry but I can't add a comment yet so I answer like that.抱歉,我还不能添加评论,所以我这样回答。
I changed that function to:我将该功能更改为:

function round(array) {
var min = Math.min(...array),
    max = Math.max(...array),
    spacing = (max - min) / (max - 1),
    fixed = Math.ceil(-Math.log10(spacing));

if (fixed < 0) return array;
return array.map(v => v.toFixed(fixed));
}

And the result looks good.结果看起来不错。
Thanks!谢谢!

The reason why I changed that was because when I had more data and diff between max and min was high its return smaller / bad decimal number.我改变它的原因是因为当我有更多数据并且最大值和最小值之间的差异很高时,它的返回值较小/坏的十进制数。 With this is like I needed.有了这个就像我需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM