Truncate number to two decimal places without rounding

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

    My version for positive numbers:

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

    Fast, pretty, obvious. (version for positive numbers)

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

    If you exactly wanted to truncate to 2 digits of precision, you can go with a simple logic:

    function myFunction(number) {
      var roundedNumber = number.toFixed(2);
      if (roundedNumber > number)
      {
          roundedNumber = roundedNumber - 0.01;
      }
      return roundedNumber;
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 09:52

    Here you are. An answer that shows yet another way to solve the problem:

    // For the sake of simplicity, here is a complete function:
    function truncate(numToBeTruncated, numOfDecimals) {
        var theNumber = numToBeTruncated.toString();
        var pointIndex = theNumber.indexOf('.');
        return +(theNumber.slice(0, pointIndex > -1 ? ++numOfDecimals + pointIndex : undefined));
    }
    

    Note the use of + before the final expression. That is to convert our truncated, sliced string back to number type.

    Hope it helps!

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

    My solution in typescript (can easily be ported to JS):

    /**
     * Returns the price with correct precision as a string
     *
     * @param   price The price in decimal to be formatted.
     * @param   decimalPlaces The number of decimal places to use
     * @return  string The price in Decimal formatting.
     */
    type toDecimal = (price: number, decimalPlaces?: number) => string;
    const toDecimalOdds: toDecimal = (
      price: number,
      decimalPlaces: number = 2,
    ): string => {
      const priceString: string = price.toString();
      const pointIndex: number = priceString.indexOf('.');
    
      // Return the integer part if decimalPlaces is 0
      if (decimalPlaces === 0) {
        return priceString.substr(0, pointIndex);
      }
    
      // Return value with 0s appended after decimal if the price is an integer
      if (pointIndex === -1) {
        const padZeroString: string = '0'.repeat(decimalPlaces);
    
        return `${priceString}.${padZeroString}`;
      }
    
      // If numbers after decimal are less than decimalPlaces, append with 0s
      const padZeroLen: number = priceString.length - pointIndex - 1;
      if (padZeroLen > 0 && padZeroLen < decimalPlaces) {
        const padZeroString: string = '0'.repeat(padZeroLen);
    
        return `${priceString}${padZeroString}`;
      }
    
      return priceString.substr(0, pointIndex + decimalPlaces + 1);
    };
    

    Test cases:

      expect(filters.toDecimalOdds(3.14159)).toBe('3.14');
      expect(filters.toDecimalOdds(3.14159, 2)).toBe('3.14');
      expect(filters.toDecimalOdds(3.14159, 0)).toBe('3');
      expect(filters.toDecimalOdds(3.14159, 10)).toBe('3.1415900000');
      expect(filters.toDecimalOdds(8.2)).toBe('8.20');
    

    Any improvements?

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

    Another single-line solution :

    number = Math.trunc(number*100)/100
    

    I used 100 because you want to truncate to the second digit, but a more flexible solution would be :

    number = Math.trunc(number*Math.pow(10, digits))/Math.pow(10, digits)
    

    where digits is the amount of decimal digits to keep.

    See Math.trunc specs for details and browser compatibility.

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