Display numbers up to two decimals places without trailing zeros

后端 未结 2 1393
梦如初夏
梦如初夏 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:00

    Use Number.toFixed to round the number up to two digits and format as a string. Then use String.replace to chop off trailing zeros:

    [8.7456, 8.745, 8.74, 8.7, 8].forEach(function(num) {
      var str = num.toFixed(2).replace(/\.?0+$/, "");
      console.log(num, str);
    });

提交回复
热议问题