Display numbers up to two decimals places without trailing zeros

后端 未结 2 1389
梦如初夏
梦如初夏 2021-02-14 01:39

In my code I will be accepting multiple values, for example:

8.7456
8.7
8

and I need to have them appear as

8.74
8.7
8
         


        
2条回答
  •  盖世英雄少女心
    2021-02-14 02:13

    Multiply by 100, floor, divide by 100.

    var n = 8.7456;
    var result = Math.floor(n * 100) / 100; // 8.74
    

    Edit: if you’re looking at this question after the fact, this is probably not what you want. It satisfies the odd requirement of having 8.7456 appear as 8.74. See also the relevant comment.

提交回复
热议问题