JS smart rounding small numbers

Viewed 562

I'm looking for some algorithm to "smart" round small numbers. For example:
Let's have array with values:
0: 4.0236180709235
1: 4.02462309509067
2: 4.02412058061092
.
.
17: 4.01599998414516
18: 4.01599998414516
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))

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
1: 4.01462309509067
2: 4.03412058061092
.
.
17: 4.05599998414516
18: 4.06599998414516
19: 4.09949998319149
There I can see that decimal number for round should be 2.

Thanks!

2 Answers

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.

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.

Related