Truncate number to two decimal places without rounding

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

    I fixed using following simple way-

    var num = 15.7784514;
    Math.floor(num*100)/100;
    

    Results will be 15.77

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

    October 2017

    General solution to truncate (no rounding) a number to the n-th decimal digit and convert it to a string with exactly n decimal digits, for any n≥0.

    function toFixedTrunc(x, n) {
      const v = (typeof x === 'string' ? x : x.toString()).split('.');
      if (n <= 0) return v[0];
      let f = v[1] || '';
      if (f.length > n) return `${v[0]}.${f.substr(0,n)}`;
      while (f.length < n) f += '0';
      return `${v[0]}.${f}`
    }
    

    where x can be either a number (which gets converted into a string) or a string.

    Here are some tests for n=2 (including the one requested by OP):

    0           => 0.00
    0.01        => 0.01
    0.5839      => 0.58
    0.999       => 0.99
    1.01        => 1.01
    2           => 2.00
    2.551       => 2.55
    2.99999     => 2.99
    4.27        => 4.27
    15.7784514  => 15.77
    123.5999    => 123.59
    0.000000199 => 1.99 *
    

    * As mentioned in the note, that's due to javascript implicit conversion into exponential for "1.99e-7" And for some other values of n:

    15.001097   => 15.0010 (n=4)
    0.000003298 => 0.0000032 (n=7)
    0.000003298257899 => 0.000003298257 (n=12)
    
    0 讨论(0)
  • 2020-11-22 09:36

    These solutions do work, but to me seem unnecessarily complicated. I personally like to use the modulus operator to obtain the remainder of a division operation, and remove that. Assuming that num = 15.7784514:

    num-=num%.01;
    

    This is equivalent to saying num = num - (num % .01).

    0 讨论(0)
  • 2020-11-22 09:38
    num = 19.66752
    f = num.toFixed(3).slice(0,-1)
    alert(f)
    

    This will return 19.66

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

    parseInt is faster then 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"
    
    0 讨论(0)
  • 2020-11-22 09:42

    function formatLimitDecimals(value, decimals) {
      value = value.toString().split('.')
    
      if (value.length === 2) {
        return Number([value[0], value[1].slice(0, decimals)].join('.'))
      } else {
        return Number(value[0]);
      }
    }
    
    console.log(formatLimitDecimals(4.156, 2)); // 4.15
    console.log(formatLimitDecimals(4.156, 8)); // 4.156
    console.log(formatLimitDecimals(4.156, 0)); // 4

    0 讨论(0)
提交回复
热议问题