如有必要,如何舍入至最多 2 个小数位? [英] How to round to at most 2 decimal places, if necessary?

查看:23
本文介绍了如有必要,如何舍入至最多 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?

推荐答案

使用 Math.round() :

Math.round(num * 100) / 100

或者更具体地确保像 1.005 一样正确,使用 Number.EPSILON :

Or to be more specific and to ensure things like 1.005 round correctly, use Number.EPSILON :

Math.round((num + Number.EPSILON) * 100) / 100

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

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