簡體   English   中英

將小數位數限制為特定情況(非四舍五入)

[英]Limit decimal places to specific situations (not round)

我想限制一個數字做2小數位,但僅當其余為零時。 我不想四舍五入。

我嘗試使用此示例(1.0000).toFixed(2) ,結果將為1.00,但如果我有一個數字(1.0030).toFixed(2) ,則結果應為1.003。

我嘗試將parseFloat與toFixed結合使用,但沒有得到我想要的結果。

javascript中是否有任何功能可即時實現。

因此,您至少需要兩個小數? 這是一種方法:

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

例子:

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

如果您希望保留少於兩個小數的數字,請改用以下方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM