舍入到最多2位小数(仅在必要时) [英] Round to at most 2 decimal places (only if necessary)

查看:133
本文介绍了舍入到最多2位小数(仅在必要时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想舍入最多2位小数,但仅在必要时

I'd like to round at most 2 decimal places, but only if necessary.

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在 JavaScript 中执行此操作?

How can I do this in JavaScript?

推荐答案

您可以使用

function roundToTwo(num) {    
    return +(Math.round(num + "e+2")  + "e-2");
}

我在 MDN 。他们的方式避免了1.005的问题,即提到

I found this over on MDN. Their way avoids the problem with 1.005 that was mentioned.

roundToTwo(1.005)
1.01
roundToTwo(10)
10
roundToTwo(1.7777777)
1.78
roundToTwo(9.1)
9.1
roundToTwo(1234.5678)
1234.57

这篇关于舍入到最多2位小数(仅在必要时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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