使用javascript舍入小数 [英] round off decimal using javascript

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

问题描述

我需要使用javascript将小数值四舍五入到小数位。

I need to round off the decimal value to decimal places using javascript.

Ex,:

16.181 to 16.18
16.184 to 16.18
16.185 to 16.19
16.187 to 16.19

我找到了一些答案,但大多数都没有找到答案16.185到16.19 ..

I have found some answers, but most of them do not round off 16.185 to 16.19..

推荐答案

(Math.round((16.185*Math.pow(10,2)).toFixed(1))/Math.pow(10,2)).toFixed(2);

如果您的值是,例如16.199正常回合将返回16.2 ...但是使用这种方法你会得到最后0,所以你看到16.20!但请记住,该值将以字符串形式返回。如果你想将它用于进一步的操作,你必须解析它:)

If your value is, for example 16.199 normal round will return 16.2... but with this method youll get last 0 too, so you see 16.20! But keep in mind that the value will returned as string. If you want to use it for further operations, you have to parsefloat it :)

现在作为函数:

function trueRound(value, digits){
    return (Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits);
}

这篇关于使用javascript舍入小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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