Truncate number to two decimal places without rounding

前端 未结 30 2758
再見小時候
再見小時候 2020-11-22 09:08

Suppose I have a value of 15.7784514, I want to display it 15.77 with no rounding.

var num = parseFloat(15.7784514);
document.write(num.toFixed(1)+\"
30条回答
  •  -上瘾入骨i
    2020-11-22 09:51

    An Easy way to do it is the next but is necessary ensure that the amount parameter is given as a string.

    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
    

提交回复
热议问题