假设我有一个值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?


当前回答

一个简单的解决方案

const toFixedNoRounding = (value, digits) => {
  const factor = Math.pow(10, digits);

  return Math.trunc(value * factor) / factor;
};

其他回答

parseInt比Math.floor快

function floorFigure(figure, decimals){
    if (!decimals) decimals = 2;
    var d = Math.pow(10,decimals);
    return (parseInt(figure*d)/d).toFixed(decimals);
};

floorFigure(123.5999)    =>   "123.59"
floorFigure(123.5999, 3) =>   "123.599"

我选择写这个来手动删除剩余的字符串,这样我就不必处理数字带来的数学问题:

num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf("."))+3); //With 3 exposing the hundredths place
Number(num); //If you need it back as a Number

这将得到“15.77”,其中num = 15.7784514;

简单的做这个

number = parseInt(number * 100)/100;

最有效的解决方案(对于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