显示数字,最多两位小数,不带零 [英] Display numbers up to two decimals places without trailing zeros
本文介绍了显示数字,最多两位小数,不带零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的代码中,我将接受多个值,例如:
In my code I will be accepting multiple values, for example:
8.7456
8.7
8
,我需要让它们显示为
8.74
8.7
8
即显示最多两位小数.
我知道.toFixed(2)
将帮助我获得第一个值,但是在第二个和第三个值上会有我不希望出现的尾随零.
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?
推荐答案
使用 String.replace
截断尾随零:
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"
这篇关于显示数字,最多两位小数,不带零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文