[removed] Round to a number of decimal places, but strip extra zeros

前端 未结 8 2186
鱼传尺愫
鱼传尺愫 2020-12-02 12:00

Here\'s the scenario: I\'m getting .9999999999999999 when I should be getting 1.0.
I can afford to lose a decimal place of precision, so I\'m u

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 12:34

    The toFixed() method formats a number using fixed-point notation, and returns a string.

    It applies a half-up rounding strategy.

    (0.124).toFixed(2); // returns 0.12
    (0.125).toFixed(2); // returns 0.13
    

    As you described, it will indeed also result in (potentially unnecessary) trailing zeroes sometimes.

    (0.001).toFixed(2); // returns 0.00
    

    You may not want to get rid of those trailing zeroes, essentially you could just convert it back to a number. There are many ways to do this.

    +(0.001).toFixed(2); // the shortest
    

    For an overview, of the different methods to convert strings to numbers, please check this question, which has some excellent answers.

提交回复
热议问题