在JavaScript中,当从浮点数转换为字符串时,如何才能在小数点后得到2位数字?例如,0.34而不是0.3445434。


当前回答

/** don't spend 5 minutes, use my code **/
function prettyFloat(x,nbDec) { 
    if (!nbDec) nbDec = 100;
    var a = Math.abs(x);
    var e = Math.floor(a);
    var d = Math.round((a-e)*nbDec); if (d == nbDec) { d=0; e++; }
    var signStr = (x<0) ? "-" : " ";
    var decStr = d.toString(); var tmp = 10; while(tmp<nbDec && d*tmp < nbDec) {decStr = "0"+decStr; tmp*=10;}
    var eStr = e.toString();
    return signStr+eStr+"."+decStr;
}

prettyFloat(0);      //  "0.00"
prettyFloat(-1);     // "-1.00"
prettyFloat(-0.999); // "-1.00"
prettyFloat(0.5);    //  "0.50"

其他回答

我认为这里的关键是首先正确地舍入,然后您可以将其转换为String。

function roundOf(n, p) {
    const n1 = n * Math.pow(10, p + 1);
    const n2 = Math.floor(n1 / 10);
    if (n1 >= (n2 * 10 + 5)) {
        return (n2 + 1) / Math.pow(10, p);
    }
    return n2 / Math.pow(10, p);
}

// All edge cases listed in this thread
roundOf(95.345, 2); // 95.35
roundOf(95.344, 2); // 95.34
roundOf(5.0364342423, 2); // 5.04
roundOf(0.595, 2); // 0.60
roundOf(0.335, 2); // 0.34
roundOf(0.345, 2); // 0.35
roundOf(551.175, 2); // 551.18
roundOf(0.3445434, 2); // 0.34

现在可以使用toFixed(p)安全地格式化这个值。 在你的具体案例中

roundOf(0.3445434, 2).toFixed(2); // 0.34

也许你还需要小数分隔符?这是我刚刚创建的一个函数:

function formatFloat(num,casasDec,sepDecimal,sepMilhar) {
    if (num < 0)
    {
        num = -num;
        sinal = -1;
    } else
        sinal = 1;
    var resposta = "";
    var part = "";
    if (num != Math.floor(num)) // decimal values present
    {
        part = Math.round((num-Math.floor(num))*Math.pow(10,casasDec)).toString(); // transforms decimal part into integer (rounded)
        while (part.length < casasDec)
            part = '0'+part;
        if (casasDec > 0)
        {
            resposta = sepDecimal+part;
            num = Math.floor(num);
        } else
            num = Math.round(num);
    } // end of decimal part
    while (num > 0) // integer part
    {
        part = (num - Math.floor(num/1000)*1000).toString(); // part = three less significant digits
        num = Math.floor(num/1000);
        if (num > 0)
            while (part.length < 3) // 123.023.123  if sepMilhar = '.'
                part = '0'+part; // 023
        resposta = part+resposta;
        if (num > 0)
            resposta = sepMilhar+resposta;
    }
    if (sinal < 0)
        resposta = '-'+resposta;
    return resposta;
}
var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding

countDecimals = value => { if (Math.floor(value) === value) return 0; let stringValue = value.toString().split(".")[1]; if (stringValue) { return value.toString().split(".")[1].length ? value.toString().split(".")[1].length : 0; } else { return 0; } }; formatNumber=(ans)=>{ let decimalPlaces = this.countDecimals(ans); ans = 1 * ans; if (decimalPlaces !== 0) { let onePlusAns = ans + 1; let decimalOnePlus = this.countDecimals(onePlusAns); if (decimalOnePlus < decimalPlaces) { ans = ans.toFixed(decimalPlaces - 1).replace(/\.?0*$/, ""); } else { let tenMulAns = ans * 10; let decimalTenMul = this.countDecimals(tenMulAns); if (decimalTenMul + 1 < decimalPlaces) { ans = ans.toFixed(decimalPlaces - 1).replace(/\.?0*$/, ""); } } } }

我只是给这个值加上1,然后数出原始值和增加的值中出现的十进制数字。如果我在比原始十进制数字少加1之后找到十进制数字,我只调用toFixed() with(原始小数- 1)。我还通过将原始值乘以10来检查,并遵循相同的逻辑,以防加1不会减少冗余小数位。 在JS中处理浮点数舍入的简单变通方法。我试过的大多数情况下都有效。

使用乘法器的所有解都存在一个问题。不幸的是,kkyy和Christoph的解决方案都是错误的。

请测试数字551.175的小数点后2位-它将四舍五入为551.17,而它应该是551.18 !但是如果你测试的是451.175,就可以了- 451.18。所以第一眼很难发现这个错误。

问题在于乘法:尝试551.175 * 100 = 55117.49999999999 (up !)

所以我的想法是在使用Math.round()之前用toFixed()处理它;

function roundFix(number, precision)
{
    var multi = Math.pow(10, precision);
    return Math.round( (number * multi).toFixed(precision + 1) ) / multi;
}