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


当前回答

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

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

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

其他回答

Gumbo的第二个解决方案,使用正则表达式,可以工作,但由于使用正则表达式,速度较慢。由于浮点数不精确,Gumbo的第一个解决方案在某些情况下会失败。有关演示和基准测试,请参阅JSFiddle。在我目前使用的3.30 GHz Intel酷睿i5-2500 CPU系统上,第二个解决方案每次调用大约需要1636纳秒。

我所编写的解决方案包括添加一个小的补偿来处理浮点的不精确性。它基本上是瞬时的,即在纳秒的数量级上。我每次调用的时间是2纳秒,但JavaScript计时器不是非常精确或粒度。下面是JS的Fiddle和代码。

function toFixedWithoutRounding (value, precision)
{
    var factorError = Math.pow(10, 14);
    var factorTruncate = Math.pow(10, 14 - precision);
    var factorDecimal = Math.pow(10, precision);
    return Math.floor(Math.floor(value * factorError + 1) / factorTruncate) / factorDecimal;
}

var values = [1.1299999999, 1.13, 1.139999999, 1.14, 1.14000000001, 1.13 * 100];

for (var i = 0; i < values.length; i++)
{
    var value = values[i];
    console.log(value + " --> " + toFixedWithoutRounding(value, 2));
}

for (var i = 0; i < values.length; i++)
{
    var value = values[i];
    console.log(value + " --> " + toFixedWithoutRounding(value, 4));
}

console.log("type of result is " + typeof toFixedWithoutRounding(1.13 * 100 / 100, 2));

// Benchmark
var value = 1.13 * 100;
var startTime = new Date();
var numRun = 1000000;
var nanosecondsPerMilliseconds = 1000000;

for (var run = 0; run < numRun; run++)
    toFixedWithoutRounding(value, 2);

var endTime = new Date();
var timeDiffNs = nanosecondsPerMilliseconds * (endTime - startTime);
var timePerCallNs = timeDiffNs / numRun;
console.log("Time per call (nanoseconds): " + timePerCallNs);

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

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

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

希望能有所帮助!

2021年6月更新

这将固定任何给定长度的数字而不舍入

let fixwithoutsurround = (v, l) => { const intPart = Math.trunc(v).toString() const fractionPart = v.toString().slice(v.toString(). indexof ('.') + 1) 如果(fractionPart。长度> l) { 返回(intPart.concat(数量”。’,fractionPart。片(0,l))) }其他{ const padding = intPart.concat('。’,fractionPart。padEnd (l ' 0 ')) 返回的 } } 12) console.log (FixWithoutRounding (123.123)

滚动你自己的固定函数:为正值数学。地板很好。

function toFixed(num, fixed) {
    fixed = fixed || 0;
    fixed = Math.pow(10, fixed);
    return Math.floor(num * fixed) / fixed;
}

对于负数,数学。底部是值的整数。所以你可以用数学。装天花板。

的例子,

Math.ceil(-15.778665 * 10000) / 10000 = -15.7786
Math.floor(-15.778665 * 10000) / 10000 = -15.7787 // wrong.

这些解决方案确实有效,但对我来说似乎没有必要这么复杂。我个人喜欢用模运算符来得到除法运算的余数,然后去掉余数。假设num = 15.7784514:

num-=num%.01;

这相当于说num = num - (num % .01)。