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


当前回答

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

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

其他回答

将数字转换为字符串,匹配到小数点后第二位:

功能召唤(形式) 原型。值,圆 var with2Decimals toString () = num。竞赛(- ^ \ d + (? d: \。{0.2的)? /)[0 - 9] rounded。价值2决定 的 <形式onsubmit=“报复性calc(this)”> 原始号码:<输入方式/> <br /> ' Rounded number: < name name=" Rounded" type="文本" placeholder="readonly" readonly> < / form >

与toString不同,toFixed方法在某些情况下会失败,所以要非常小心。

更新(2021年1月)

Depending on its range, a number in javascript may be shown in scientific notation. For example, if you type 0.0000001 in the console, you may see it as 1e-7, whereas 0.000001 appears unchanged (0.000001). If your application works on a range of numbers for which scientific notation is not involved, you can just ignore this update and use the original answer below.

这次更新增加了一个函数,检查数字是否为科学格式,如果是,则将其转换为十进制格式。在这里我建议使用这个函数,但你可以根据应用程序的需要使用任何其他函数来实现相同的目标:

function toFixed(x) {
  if (Math.abs(x) < 1.0) {
    let e = parseInt(x.toString().split('e-')[1]);
    if (e) {
        x *= Math.pow(10,e-1);
        x = '0.' + (new Array(e)).join('0') + x.toString().substring(2);
    }
  } else {
    let e = parseInt(x.toString().split('+')[1]);
    if (e > 20) {
        e -= 20;
        x /= Math.pow(10,e);
        x += (new Array(e+1)).join('0');
    }
  }
  return x;
}

现在只需将该函数应用于参数(这是相对于原始答案的唯一变化):

function toFixedTrunc(x, n) {
      x = toFixed(x) 

      // From here on the code is the same than the original answer
      const v = (typeof x === 'string' ? x : x.toString()).split('.');
      if (n <= 0) return v[0];
      let f = v[1] || '';
      if (f.length > n) return `${v[0]}.${f.substr(0,n)}`;
      while (f.length < n) f += '0';
      return `${v[0]}.${f}`
    }

这个更新的版本还解决了一个评论中提到的情况:

toFixedTrunc(0.000000199, 2) => "0.00" 

同样,选择最适合应用程序需求的。

原答案(2017年10月)

General solution to truncate (no rounding) a number to the n-th decimal digit and convert it to a string with exactly n decimal digits, for any n≥0.
function toFixedTrunc(x, n) {
  const v = (typeof x === 'string' ? x : x.toString()).split('.');
  if (n <= 0) return v[0];
  let f = v[1] || '';
  if (f.length > n) return `${v[0]}.${f.substr(0,n)}`;
  while (f.length < n) f += '0';
  return `${v[0]}.${f}`
}

其中x可以是一个数字(转换为字符串)或字符串。

下面是n=2的一些测试(包括OP要求的测试):

0           => 0.00
0.01        => 0.01
0.5839      => 0.58
0.999       => 0.99
1.01        => 1.01
2           => 2.00
2.551       => 2.55
2.99999     => 2.99
4.27        => 4.27
15.7784514  => 15.77
123.5999    => 123.59

对于n的其它值:

15.001097   => 15.0010 (n=4)
0.000003298 => 0.0000032 (n=7)
0.000003298257899 => 0.000003298257 (n=12)

另一个单线解决方案:

number = Math.trunc(number*100)/100

我使用100是因为你想截断到第二位,但更灵活的解决方案是:

number = Math.trunc(number*Math.pow(10, digits))/Math.pow(10, digits)

其中digits是要保留的十进制数字的数量。

看数学。详细信息和浏览器兼容性的Trunc规范。

这里的答案对我没有帮助,它总是四舍五入,或者给我错误的小数。

我的解决方案将您的小数转换为字符串,提取字符,然后将整个东西作为数字返回。

function Dec2(num) {
  num = String(num);
  if(num.indexOf('.') !== -1) {
    var numarr = num.split(".");
    if (numarr.length == 1) {
      return Number(num);
    }
    else {
      return Number(numarr[0]+"."+numarr[1].charAt(0)+numarr[1].charAt(1));
    }
  }
  else {
    return Number(num);
  }  
}

Dec2(99); // 99
Dec2(99.9999999); // 99.99
Dec2(99.35154); // 99.35
Dec2(99.8); // 99.8
Dec2(10265.985475); // 10265.98

如果你想精确地截断为2位精度,你可以使用一个简单的逻辑:

function myFunction(number) {
  var roundedNumber = number.toFixed(2);
  if (roundedNumber > number)
  {
      roundedNumber = roundedNumber - 0.01;
  }
  return roundedNumber;
}