user8816462
user8816462

Reputation:

Round to nearest decimal number with small amount of decimal places

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.

Upvotes: 2

Views: 108

Answers (1)

user8811940
user8811940

Reputation:

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
    ));
}

Upvotes: 1

Related Questions