2

I have decimal numbers and I need to round it to have as small amount of decimal places as possible.

For Example :

0.0812321321 -> 0.1

0.001232123 -> 0.001

0.00001535865586 -> 0.00002

I was thinking about finding the nearest higher multiple of 10, so the examples would have these results: 0.1; 0.01; 0.0001. For my project it's close enough but I am not able to create a function that would do that.

  • 2
    Sure, well, what did you try? A hack solution would be to smash this into a string and regex snip off all the stuff you don't want. That won't handle rounding though. – tadman Oct 22 '17 at 23:02
  • 3
    Possible duplicate of [Round to at most 2 decimal places (only if necessary)](https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary) – hoffm Oct 22 '17 at 23:12

1 Answers1

1
function nearestDecimal(number) {
    if (!number) {
        return "0";
    }
    const decimals = -Math.log10(number);
    const integerPart = Math.floor(decimals);
    const fractionalPart = decimals - integerPart;
    return number.toFixed(Math.max(0,
        fractionalPart >= -Math.log10(.5) ? Math.ceil(decimals) : integerPart
    ));
}