Formatting a number with exactly two decimals in JavaScript

后端 未结 30 2221
广开言路
广开言路 2020-11-21 06:29

I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can

30条回答
  •  死守一世寂寞
    2020-11-21 06:57

    Here's a TypeScript implementation of https://stackoverflow.com/a/21323330/916734. It also dries things up with functions, and allows for a optional digit offset.

    export function round(rawValue: number | string, precision = 0, fractionDigitOffset = 0): number | string {
      const value = Number(rawValue);
      if (isNaN(value)) return rawValue;
    
      precision = Number(precision);
      if (precision % 1 !== 0) return NaN;
    
      let [ stringValue, exponent ] = scientificNotationToParts(value);
    
      let shiftExponent = exponentForPrecision(exponent, precision, Shift.Right);
      const enlargedValue = toScientificNotation(stringValue, shiftExponent);
      const roundedValue = Math.round(enlargedValue);
    
      [ stringValue, exponent ] = scientificNotationToParts(roundedValue);
      const precisionWithOffset = precision + fractionDigitOffset;
      shiftExponent = exponentForPrecision(exponent, precisionWithOffset, Shift.Left);
    
      return toScientificNotation(stringValue, shiftExponent);
    }
    
    enum Shift {
      Left = -1,
      Right = 1,
    }
    
    function scientificNotationToParts(value: number): Array {
      const [ stringValue, exponent ] = value.toString().split('e');
      return [ stringValue, exponent ];
    }
    
    function exponentForPrecision(exponent: string, precision: number, shift: Shift): number {
      precision = shift * precision;
      return exponent ? (Number(exponent) + precision) : precision;
    }
    
    function toScientificNotation(value: string, exponent: number): number {
      return Number(`${value}e${exponent}`);
    }
    

提交回复
热议问题