Javascript 将小数位数限制在特定情况下(不四舍五入)

Javascript 将小数位数限制在特定情况下(不四舍五入),javascript,Javascript,我想把一个数字限制在小数点后2位,但只有当其余的数字为零时。我不想把数字四舍五入 我试着用这个例子 (1.0000).toFixed(2) 结果应该是1.00,但是如果我有一个像(1.0030)这样的数字。如果固定(2),结果应该是1.003 我尝试将parseFloat与toFixed组合使用,但没有得到我想要的结果 javascript中是否有任何函数可以实现我想要实现的功能。所以您希望最小值为两位小数?这里有一个方法: function toMinTwoDecimals(numString

我想把一个数字限制在小数点后2位,但只有当其余的数字为零时。我不想把数字四舍五入

我试着用这个例子
(1.0000).toFixed(2)
结果应该是1.00,但是如果我有一个像
(1.0030)这样的数字。如果固定(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);
}

仅仅使用舍入函数是无法做到这一点的。您需要一些逻辑来检测小数的数量,然后应用适当的格式。@Dalorzo阅读文章,我不想对数字进行四舍五入。。。