Truncate number to two decimal places without rounding

前端 未结 30 3265
再見小時候
再見小時候 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: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
    

提交回复
热议问题