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


当前回答

下面是另一个保存.toFixed([digits])函数而不舍入浮点变量的变体:

Number.prototype.toRealFixed = function(digits) {
    return Math.floor(this.valueOf() * Math.pow(10, digits)) / Math.pow(10, digits);
};

和要求:

var float_var = 0.02209062;
float_var.toRealFixed();

其他回答

下面是另一个保存.toFixed([digits])函数而不舍入浮点变量的变体:

Number.prototype.toRealFixed = function(digits) {
    return Math.floor(this.valueOf() * Math.pow(10, digits)) / Math.pow(10, digits);
};

和要求:

var float_var = 0.02209062;
float_var.toRealFixed();

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

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

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

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

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

参考答案

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

谢谢你!

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

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;
};