Javascript:将舍入数字格式化为N个小数 [英] Javascript: formatting a rounded number to N decimals

查看:173
本文介绍了Javascript:将舍入数字格式化为N个小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,将数字舍入到N个小数位的典型方法如下:

in JavaScript, the typical way to round a number to N decimal places is something like:

function round_number(num, dec) {
    return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}

然而,此方法将舍入到最大 N小数位,而我想总是舍入到N个小数位。例如,2.0将四舍五入为2。

However this approach will round to a maximum of N decimal places while I want to always round to N decimal places. For example "2.0" would be rounded to "2".

任何想法?

推荐答案

这不是一个四舍五入的问题,那个是一个显示问题。数字不包含有效数字的信息;值2与2.0000000000000相同。当您将舍入值转换为字符串时,它会使其显示一定数量的数字。

That's not a rounding ploblem, that is a display problem. A number doesn't contain information about significant digits; the value 2 is the same as 2.0000000000000. It's when you turn the rounded value into a string that you have make it display a certain number of digits.

您可以在数字后添加零,例如:

You could just add zeroes after the number, something like:

var s = number.toString();
if (s.indexOf('.') == -1) s += '.';
while (s.length < s.indexOf('.') + 4) s += '0';

(注意,这假设客户端的区域设置使用句点作为小数分隔符,代码需要还有一些工作可以用于其他设置。)

(Note that this assumes that the regional settings of the client uses period as decimal separator, the code needs some more work to function for other settings.)

这篇关于Javascript:将舍入数字格式化为N个小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆