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


当前回答

这并不是一个安全的替代方法,因为许多其他的例子都将数字转换为指数符号,这个函数没有覆盖这个场景

// typescript // function formatLimitDecimals(value: number, decimals: number): number { function formatLimitDecimals(value, decimals) { const stringValue = value.toString(); if(stringValue.includes('e')) { // TODO: remove exponential notation throw 'invald number'; } else { const [integerPart, decimalPart] = stringValue.split('.'); if(decimalPart) { return +[integerPart, decimalPart.slice(0, decimals)].join('.') } else { return integerPart; } } } console.log(formatLimitDecimals(4.156, 2)); // 4.15 console.log(formatLimitDecimals(4.156, 8)); // 4.156 console.log(formatLimitDecimals(4.156, 0)); // 4 console.log(formatLimitDecimals(0, 4)); // 0 // not covered console.log(formatLimitDecimals(0.000000199, 2)); // 0.00

其他回答

2016年11月5日更新

新的答案,总是准确的

function toFixed(num, fixed) {
    var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?');
    return num.toString().match(re)[0];
}

由于javascript中的浮点数学总是有边缘情况,所以之前的解决方案在大多数情况下都是准确的,这是不够的。 有一些解决方案,如num.toPrecision, BigDecimal.js和accounting.js。 然而,我相信仅仅解析字符串是最简单的,而且总是准确的。

基于@Gumbo接受的答案的良好编写的正则表达式的更新,这个新的toFixed函数将始终按预期工作。


老答案,并不总是准确的。

固定功能:

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

我的解决方案在typescript(可以很容易地移植到JS):

/**
 * Returns the price with correct precision as a string
 *
 * @param   price The price in decimal to be formatted.
 * @param   decimalPlaces The number of decimal places to use
 * @return  string The price in Decimal formatting.
 */
type toDecimal = (price: number, decimalPlaces?: number) => string;
const toDecimalOdds: toDecimal = (
  price: number,
  decimalPlaces: number = 2,
): string => {
  const priceString: string = price.toString();
  const pointIndex: number = priceString.indexOf('.');

  // Return the integer part if decimalPlaces is 0
  if (decimalPlaces === 0) {
    return priceString.substr(0, pointIndex);
  }

  // Return value with 0s appended after decimal if the price is an integer
  if (pointIndex === -1) {
    const padZeroString: string = '0'.repeat(decimalPlaces);

    return `${priceString}.${padZeroString}`;
  }

  // If numbers after decimal are less than decimalPlaces, append with 0s
  const padZeroLen: number = priceString.length - pointIndex - 1;
  if (padZeroLen > 0 && padZeroLen < decimalPlaces) {
    const padZeroString: string = '0'.repeat(padZeroLen);

    return `${priceString}${padZeroString}`;
  }

  return priceString.substr(0, pointIndex + decimalPlaces + 1);
};

测试用例:

  expect(filters.toDecimalOdds(3.14159)).toBe('3.14');
  expect(filters.toDecimalOdds(3.14159, 2)).toBe('3.14');
  expect(filters.toDecimalOdds(3.14159, 0)).toBe('3');
  expect(filters.toDecimalOdds(3.14159, 10)).toBe('3.1415900000');
  expect(filters.toDecimalOdds(8.2)).toBe('8.20');

任何改善吗?

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

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.

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)

更新(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)