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

前端 未结 8 2189
鱼传尺愫
鱼传尺愫 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:14

    None of these really got me what I was looking for based on the question title, which was, for example, for 5.00 to be 5 and 5.10 to be 5.1. My solution was as follows:

    num.toFixed(places).replace(/\.?0+$/, '')
    
    '5.00'.replace(/\.?0+$/, '') // 5
    '5.10'.replace(/\.?0+$/, '') // 5.1
    '5.0000001'.replace(/\.?0+$/, '') // 5.0000001
    '5.0001000'.replace(/\.?0+$/, '') // 5.0001
    

    Note: The regex only works if places > 0

    P.S. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

提交回复
热议问题