在 Python 中四舍五入到第二个小数位 [英] Round up to Second Decimal Place in Python

查看:36
本文介绍了在 Python 中四舍五入到第二个小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在python中将数字四舍五入到小数点后第二位?例如:

How can I round up a number to the second decimal place in python? For example:

0.022499999999999999

应该四舍五入到 0.03

0.1111111111111000

应该四舍五入到 0.12

如果小数点后第三位有任何值,我希望它总是四舍五入,在小数点后留下 2 个值.

If there is any value in the third decimal place, I want it to always round up leaving me 2 values behind the decimal point.

推荐答案

Python 包含 round() 函数,该函数让您指定您想要的位数.来自文档:

Python includes the round() function which lets you specify the number of digits you want. From the documentation:

round(x[, n])

返回四舍五入到小数点后n位的浮点值x.如果省略 n,则默认为零.结果是一个浮点数.值四舍五入到最接近的 10 的幂减去 n 的倍数;如果两个倍数相等,则从 0 开始舍入(例如,round(0.5) 为 1.0,round(-0.5) 为 -1.0).

Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).

所以你会想要使用 round(x, 2) 来做普通的舍入.为了确保数字总是四舍五入向上,您需要使用 ceil(x) 函数.类似地,要舍入向下,请使用floor(x).

So you would want to use round(x, 2) to do normal rounding. To ensure that the number is always rounded up you would need to use the ceil(x) function. Similarly, to round down use floor(x).

这篇关于在 Python 中四舍五入到第二个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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