Marco Santos
Marco Santos

Reputation: 1005

Limit decimal places to specific situations (not round)

Im looking to limit a number do 2 decimal places, but only when the rest is zero. I dont want to round the numbers.

I tried using this example (1.0000).toFixed(2) the result would be 1.00, but if i have a number like (1.0030).toFixed(2), the result should be 1.003.

I tried using parseFloat with a combination of toFixed but doesn´t get the result i want.

Is there any function in javascript that does what im trying to achieve.

Upvotes: 1

Views: 84

Answers (1)

Viktor
Viktor

Reputation: 3536

So you want a minimum of two decimals? Here's one way:

function toMinTwoDecimals(numString) {
    var num = parseFloat(numString);
    return num == num.toFixed(2) ? num.toFixed(2) : num.toString();
}

Examples:

toMinTwoDecimals("1.0030"); // returns "1.003"
toMinTwoDecimals("1.0000"); // returns "1.00"
toMinTwoDecimals("1"); // returns "1.00"
toMinTwoDecimals("-5.24342234"); // returns "-5.24342234"

In case you want to leave numbers with less than two decimals untouched, use this instead:

function toMinTwoDecimals(numString) {
    var num = parseFloat(numString);

    // Trim extra zeros for numbers with three or more 
    // significant decimals (e.g. "1.0030" => "1.003")
    if (num != num.toFixed(2)) {
        return num.toString();
    }

    // Leave numbers with zero or one decimal untouched
    // (e.g. "5", "1.3")
    if (numString === num.toFixed(0) || numString === num.toFixed(1)) {
        return numString;
    }

    // Limit to two decimals for numbers with extra zeros
    // (e.g. "1.0000" => "1.00", "1.1000000" => "1.10")
    return num.toFixed(2);
}

Upvotes: 2

Related Questions