在 Javascript 中四舍五入到最小 2 位小数和最大 4 位小数

Round to minimum of 2 decimals and max of 4 decimals in Javascript

有没有办法将数字四舍五入到最小 2 位小数 i javascript.

示例:

  1. 10 -> 10.00
  2. 20.10 -> 20.10
  3. 30.1234 -> 30.1234
  4. 40.123456 -> 40.1235
  5. 50.1200 -> 50.12
  6. 60.123 -> 60.123

依此类推...所以四舍五入到最小 2 位小数。我可以为此使用 jquery。

看看 toFixed() javascript 函数:here

它保留为字符串,但可能会导致问题,具体取决于您的操作

听起来就像你说你想把数字转换成至少有两位小数(即使它们是零)和最多四位(如果需要的话)的字符串(它们不是零)。如果是:

对于所有现代浏览器:

如果你不能依赖Intl:我唯一能想到的就是使用toFixed(4)然后删除最多两个尾随零:

function format(num) {
  var str = num.toFixed(4);
  return str.replace(/0{1,2}$/, '');
}
function test(test) {
  var result = format(test.num);
  console.log(
    test.num,
    "=>",
    result,
    result == test.result ? "- Pass" : "- Fail"
  );
}

[
    {num: 10, result:  "10.00"},
    {num: 20.10, result:  "20.10"},
    {num: 30.1234, result:  "30.1234"},
    {num: 40.123456, result:  "40.1235"},
    {num: 50.1200, result:  "50.12"},
    {num: 60.123, result:  "60.123"}
].forEach(test);

如果您不局限于过时的浏览器,我推荐这个智能功能:

var fmtr = new Intl.NumberFormat('us-us', {
  style: 'decimal',
  useGrouping: false,
  minimumFractionDigits: 2,
  maximumFractionDigits: 4
});

function test(test) {
  var result = fmtr.format(test.num);
  console.log(
    test.num,
    "=>",
    result,
    result == test.result ? "- Pass" : "- Fail"
  );
}

[
    {num: 10, result:  "10.00"},
    {num: 20.10, result:  "20.10"},
    {num: 30.1234, result:  "30.1234"},
    {num: 40.123456, result:  "40.1235"},
    {num: 50.1200, result:  "50.12"},
    {num: 60.123, result:  "60.123"}
].forEach(test);

参考文献:

所选解决方案仅适用于 4 位小数。不是5个或更多。如果您仅限于使用过时的浏览器,下面的强大代码会删除所有尾随零,然后在 none 剩余的情况下添加 2 个零。

function format(n) {

  let r = (+n).toFixed(10); // or any

  if (r.match(/\./)) {
      r = r.replace(/\.?0+$/, '');
  }

  const s = r.toString();

  if (s.indexOf('.') === -1) {
      r = Number.parseFloat(r).toFixed(2);
  }

  return r;
}

我需要这样的东西,但它可以处理任何数量的小数,而且不限于过时的浏览器。

这是尚未提出的可能解决方案之一,我发布了它,希望有人可以评论如何将其简化为仅正则表达式。谢谢!