如何在python中对小数部分进行向上和向下舍入

问题描述 投票:0回答:2

如何在 pytho 中对小数值进行向下舍入和向上舍入。

用户输入

a = 2.336  After round up it should be like a = 2.34
a = 4.13623  After round up it should be like a = 4.14

python中有没有内置函数可以操作

python
2个回答
2
投票

你可以尝试类似的事情

a = 2.336
a = math.ceil(a*pow(10,2))/pow(10,2)

这里

2
中的
pow(10,2)
代表你需要的小数点后面的精度


1
投票

您可以使用 math

 模块中的 
ceil()
floor() 函数。这里有一些代码可以帮助您入门。

def round_up(n, decimals=0):
   multiplier = 10 ** decimals
   return math.ceil(n * multiplier) / multiplier

尝试弄清楚小数和乘数变量在这里是如何工作的。

© www.soinside.com 2019 - 2024. All rights reserved.