Truncate number to two decimal places without rounding

前端 未结 30 2655
再見小時候
再見小時候 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条回答
  • 2020-11-22 09:42

    Roll your own toFixed function: for positive values Math.floor works fine.

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

    For negative values Math.floor is round of the values. So you can use Math.ceil instead.

    Example,

    Math.ceil(-15.778665 * 10000) / 10000 = -15.7786
    Math.floor(-15.778665 * 10000) / 10000 = -15.7787 // wrong.
    
    0 讨论(0)
  • 2020-11-22 09:42

    The most efficient solution (for 2 fraction digits) is to subtract 0.005 before calling toFixed()

    function toFixed2( num ) { return (num-0.005).toFixed(2) }
    

    Negative numbers will be rounded down too (away from zero). The OP didn't tell anything about negative numbers.

    0 讨论(0)
  • 2020-11-22 09:43

    truncate without zeroes

    function toTrunc(value,n){  
        return Math.floor(value*Math.pow(10,n))/(Math.pow(10,n));
    }
    

    or

    function toTrunc(value,n){
        x=(value.toString()+".0").split(".");
        return parseFloat(x[0]+"."+x[1].substr(0,n));
    }
    

    test:

    toTrunc(17.4532,2)  //17.45
    toTrunc(177.4532,1) //177.4
    toTrunc(1.4532,1)   //1.4
    toTrunc(.4,2)       //0.4
    

    truncate with zeroes

    function toTruncFixed(value,n){
        return toTrunc(value,n).toFixed(n);
    }
    

    test:

    toTrunc(17.4532,2)  //17.45
    toTrunc(177.4532,1) //177.4
    toTrunc(1.4532,1)   //1.4
    toTrunc(.4,2)       //0.40
    
    0 讨论(0)
  • 2020-11-22 09:43

    All these answers seem a bit complicated. I would just subtract 0.5 from your number and use toFixed().

    0 讨论(0)
  • 2020-11-22 09:44

    The answers here didn't help me, it kept rounding up or giving me the wrong decimal.

    my solution converts your decimal to a string, extracts the characters and then returns the whole thing as a number.

    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
    
    0 讨论(0)
  • 2020-11-22 09:44

    The following code works very good for me:

    num.toString().match(/.\*\\..{0,2}|.\*/)[0];
    
    0 讨论(0)
提交回复
热议问题