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

其他回答

另一种解决方案是截断和舍入:

function round (number, decimals, truncate) {
    if (truncate) {
        number = number.toFixed(decimals + 1);
        return parseFloat(number.slice(0, -1));
    }

    var n = Math.pow(10.0, decimals);
    return Math.round(number * n) / n;
};

截断不带零

function toTrunc(value,n){  
    return Math.floor(value*Math.pow(10,n))/(Math.pow(10,n));
}

or

function toTrunc(value,n){
    x=(value.toString()+".0").split(".");
    return parseFloat(x[0]+"."+x[1].substr(0,n));
}

测试:

toTrunc(17.4532,2)  //17.45
toTrunc(177.4532,1) //177.4
toTrunc(1.4532,1)   //1.4
toTrunc(.4,2)       //0.4

用零截断

function toTruncFixed(value,n){
    return toTrunc(value,n).toFixed(n);
}

测试:

toTrunc(17.4532,2)  //17.45
toTrunc(177.4532,1) //177.4
toTrunc(1.4532,1)   //1.4
toTrunc(.4,2)       //0.40

不舍入得到两个浮点数更可靠。

参考答案

VaR 数 = 10.5859; var fixed2FloatPoints = parseInt(number * 100) / 100; console.log(fixed2FloatPoints);

谢谢你!

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

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;

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

所以,我这样做了:

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

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

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

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