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

其他回答

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

num-=num%.01;

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

我也面临着同样的问题,并决定在TS中使用字符串操作。

如果没有足够的小数,它将返回原始值

const getDecimalsWithoutRounding = (value: number, numberOfDecimals: number) => {
  const stringValue: string = value?.toString();
  const dotIdx: number = stringValue?.indexOf('.');
  if (dotIdx) {
    return parseFloat(stringValue.slice(0, dotIdx + numberOfDecimals + 1));
  } else {
    return value;
  }
};

console.log(getDecimalsWithoutRounding(3.34589, 2)); /// 3.34
console.log(getDecimalsWithoutRounding(null, 2));  ///null
console.log(getDecimalsWithoutRounding(55.123456789, 5)); /// 55.12345
console.log(getDecimalsWithoutRounding(10, 2));  /// 10
console.log(getDecimalsWithoutRounding(10.6, 5)); /// 10.6


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

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

为了合作,我必须使用比特币数学运算的解决方案。关键是比特币使用8个十进制数,我们不需要整数。

所以,我这样做了:

进行计算; 取这个值并设置9个小数 value = value. tofixed (9);

-去掉最后一个十进制数的子字符串:

value = value.substring(0, value.length - 1);

不。这并不优雅,但它是一个解决方案。

parseInt比Math.floor快

function floorFigure(figure, decimals){
    if (!decimals) decimals = 2;
    var d = Math.pow(10,decimals);
    return (parseInt(figure*d)/d).toFixed(decimals);
};

floorFigure(123.5999)    =>   "123.59"
floorFigure(123.5999, 3) =>   "123.599"