Display numbers up to two decimals places without trailing zeros

孤者浪人 提交于 2019-12-04 18:15:28

问题


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

i.e. display up to two decimal place.

I understand that .toFixed(2) will help me with the first value, but on the 2nd and 3rd value there will be trailing zeroes that I do not want.

How to produce my desired results?


回答1:


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).toFixed(2).replace(/\.?0+$/, ""); // "8.75"
(8.7).toFixed(2).replace(/\.?0+$/, "");    // "8.7"
(8).toFixed(2).replace(/\.?0+$/, "");      // "8"



回答2:


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.



来源:https://stackoverflow.com/questions/10215770/display-numbers-up-to-two-decimals-places-without-trailing-zeros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!