gpt4 book ai didi

javascript - 如有必要,如何舍入至多 2 位小数

转载 作者:IT老高 更新时间:2023-10-28 11:09:38 26 4
gpt4 key购买 nike

我希望最多四舍五入小数点后两位,但仅在必要时进行

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在 JavaScript 中做到这一点?

最佳答案

使用 Math.round() :

Math.round(num * 100) / 100

或者更具体地说,为了确保 1.005 等值正确舍入,请使用 Number.EPSILON :

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

关于javascript - 如有必要,如何舍入至多 2 位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11832914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com