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


当前回答

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

其他回答

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

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

num-=num%.01;

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

这是用字符串做的

export function withoutRange(number) {
  const str = String(number);
  const dotPosition = str.indexOf('.');
  if (dotPosition > 0) {
    const length = str.substring().length;
    const end = length > 3 ? 3 : length;
    return str.substring(0, dotPosition + end);
  }
  return str;
}

已经有一些合适的答案与正则表达式和算术计算,你也可以试试这个

function myFunction() {
    var str = 12.234556; 
    str = str.toString().split('.');
    var res = str[1].slice(0, 2);
    document.getElementById("demo").innerHTML = str[0]+'.'+res;
}

// output: 12.23

只需要截断数字:

function truncDigits(inputNumber, digits) {
  const fact = 10 ** digits;
  return Math.floor(inputNumber * fact) / fact;
}