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


当前回答

下面是一种简单的方法,但必须确保amount参数以字符串形式给出。

function truncate(amountAsString, decimals = 2){
  var dotIndex = amountAsString.indexOf('.');
  var toTruncate = dotIndex !== -1  && ( amountAsString.length > dotIndex + decimals + 1);
  var approach = Math.pow(10, decimals);
  var amountToTruncate = toTruncate ? amountAsString.slice(0, dotIndex + decimals +1) : amountAsString;  
  return toTruncate
    ?  Math.floor(parseFloat(amountToTruncate) * approach ) / approach
    :  parseFloat(amountAsString);

}

console.log(truncate("7.99999")); //OUTPUT ==> 7.99
console.log(truncate("7.99999", 3)); //OUTPUT ==> 7.999
console.log(truncate("12.799999999999999")); //OUTPUT ==> 7.99

其他回答

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

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

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

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

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

我也面临着同样的问题,并决定在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


我对正数的看法是:

function toFixed_norounding(n,p)
{
    var result = n.toFixed(p);
    return result <= n ? result: (result - Math.pow(0.1,p)).toFixed(p);
}

快,漂亮,明显。(正数版本)

我选择写这个来手动删除剩余的字符串,这样我就不必处理数字带来的数学问题:

num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf("."))+3); //With 3 exposing the hundredths place
Number(num); //If you need it back as a Number

这将得到“15.77”,其中num = 15.7784514;