假设我有一个值15.7784514,我想把它显示为15.77,没有舍入。

var num = parseFloat(15.7784514);
document.write(num.toFixed(1)+"<br />");
document.write(num.toFixed(2)+"<br />");
document.write(num.toFixed(3)+"<br />");
document.write(num.toFixed(10));

结果:

15.8
15.78
15.778
15.7784514000 

如何显示15.77?


当前回答

给你。另一种解决问题的方法:

// For the sake of simplicity, here is a complete function:
function truncate(numToBeTruncated, numOfDecimals) {
    var theNumber = numToBeTruncated.toString();
    var pointIndex = theNumber.indexOf('.');
    return +(theNumber.slice(0, pointIndex > -1 ? ++numOfDecimals + pointIndex : undefined));
}

注意在最后一个表达式之前使用了+。这就是将截断的、切片的字符串转换回数字类型。

希望能有所帮助!

其他回答

最有效的解决方案(对于2个分数位数)是在调用toFixed()之前减去0.005。

function toFixed2( num ) { return (num-0.005).toFixed(2) }

负数也会四舍五入(远离零)。运算符里没有提到负数。

num = 19.66752
f = num.toFixed(3).slice(0,-1)
alert(f)

这将返回19.66

为了合作,我必须使用比特币数学运算的解决方案。关键是比特币使用8个十进制数,我们不需要整数。

所以,我这样做了:

进行计算; 取这个值并设置9个小数 value = value. tofixed (9);

-去掉最后一个十进制数的子字符串:

value = value.substring(0, value.length - 1);

不。这并不优雅,但它是一个解决方案。

我使用(num-0.05). tofixed(1)来得到第二个小数。

将数字转换为字符串,匹配到小数点后第二位:

功能召唤(形式) 原型。值,圆 var with2Decimals toString () = num。竞赛(- ^ \ d + (? d: \。{0.2的)? /)[0 - 9] rounded。价值2决定 的 <形式onsubmit=“报复性calc(this)”> 原始号码:<输入方式/> <br /> ' Rounded number: < name name=" Rounded" type="文本" placeholder="readonly" readonly> < / form >

与toString不同,toFixed方法在某些情况下会失败,所以要非常小心。