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


当前回答

有一些函数可以取整数字。例如:

var x = 5.0364342423;
print(x.toFixed(2));

将打印5.04。

编辑: 小提琴

其他回答

var result = Math.round(original*100)/100;

具体细节,以防代码不是自解释的。

编辑:…或者直接使用toFixed,就像Tim Büthe提议的那样。忘记了,谢谢你的提醒(还有点赞):)

如果你想要不带圆的字符串,你可以使用这个RegEx(可能不是最有效的方法…但是真的很简单)

(2.34567778).toString().match(/\d+\.\d{2}/)[0]
// '2.34'

我认为这里的关键是首先正确地舍入,然后您可以将其转换为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
/** 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"
var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding