javascript 最多显示两位小数,不带尾随零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10215770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:04:29  来源:igfitidea点击:

Display numbers up to two decimals places without trailing zeros

javascriptnumbersparsefloat

提问by peroija

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.

我知道这.toFixed(2)将帮助我处理第一个值,但是在第二个和第三个值上会有我不想要的尾随零。

How to produce my desired results?

如何产生我想要的结果?

回答by Salman A

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

用于Number.toFixed将数字四舍五入为两位数并格式化为字符串。然后使用String.replace截断尾随零:

(8.7456).toFixed(2).replace(/\.?0+$/, ""); // "8.75"
(8.7).toFixed(2).replace(/\.?0+$/, "");    // "8.7"
(8).toFixed(2).replace(/\.?0+$/, "");      // "8"

回答by Ry-

Multiply by 100, floor, divide by 100.

乘以 100,floor除以 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.7456appear as 8.74. See also the relevant comment.

编辑:如果您事后查看这个问题,这可能不是您想要的。它满足了8.7456出现为的奇怪要求8.74。另请参阅相关评论