Truncate number to two decimal places without rounding

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

提交回复
热议问题