如何使用 Python 将浮点数四舍五入为小数点后 2 位?
在本文中,我们将向您展示如何在 Python 中将浮点数四舍五入为小数点后 2 位。以下是完成此任务的各种方法:
使用 round() 函数
使用 format() 函数
使用 Decimal 模块
使用 ceil() 函数
使用 round() 函数
round() 函数给出具有指定小数位数的浮点数,该浮点数是指定数字的四舍五入版本。
该函数将返回最接近的整数,因为小数位数的默认值为 0。
语法
round(number, digits)
参数
number(必需)- 应四舍五入的数字
digits(可选)- 最多为要四舍五入的小数位数。 0 为默认值。
算法(步骤)
以下是执行所需任务需要遵循的算法/步骤 –。
创建一个变量来存储输入的数字。
将输入 number, 2(十进制值)作为参数传递给 round() 函数,以将输入的数字四舍五入到小数点后 2 位。
打印输入浮点数的四舍五入值,精确到2位小数。
示例
以下程序使用 round() 函数返回输入浮点数的四舍五入值,精确到 2 位小数–
# input floating-point number inputNumber = 3.367824 # rounding the number up to 2 decimal places roundedNumber = round(inputNumber, 2) # print the rounded value of floating-point number up to 2 decimals print("Rounding 3.367824 upto 2 decimal places:", roundedNumber)
输出
执行时,上述程序将生成以下输出 –
Rounding 3.367824 upto 2 decimal places: 3.37
使用 format() 函数
算法(步骤)
以下是执行所需任务需要遵循的算法/步骤 –。
创建一个变量来存储输入的浮点数。
使用 format() 函数(它返回由格式说明符指定的输入值的格式化版本)通过将输入数字、格式(保留 2 位小数)作为参数传递给它,将数字四舍五入到小数点后 2 位。
示例
以下程序使用 format() 函数返回输入浮点数的四舍五入值,保留 2 位小数 –
# input floating-point number inputNumber = 4.56782 # rounding the number upto 2 decimal places print("Rounding 4.56782 upto 2 decimal places:", format(inputNumber,".2f"))
输出
执行时,上述程序将生成以下输出 –
Rounding 4.56782 upto 2 decimal places: 4.57
使用 Decimal 模块
Python 的 ceil() 函数(返回数字的上限值,即大于或等于数字的最小整数),将数字四舍五入到小数点后 2 位并打印结果数字。
如果要四舍五入到 1、2、3、4... 小数,则分别乘以和除以 # 10、100、1000、10000 个数字
示例
以下程序使用 ceil() 函数返回输入浮点数四舍五入到小数点后 2 位的值 –
# importing math module import math # input floating-point number inputNumber = 4.56782 # rounding the number upto 2 decimal places using ceil() function # If you want to round upto 1, 2, 3, 4...decimals then multiply and divide by # 10, 100, 1000, 10000 numbers respectively print("Rounding 4.56782 upto 2 decimal places:") print(math.ceil(inputNumber*100)/100)
输出
执行时,上述程序将生成以下输出 –
Input floating-point number: 35.65782 Rounding 4.56782 upto 2 decimal places: 4.57
结论
在本文中,我们学习了如何使用四种不同的方法在 Python 中将给定的浮点数四舍五入到小数点后两位。使用 ceil 函数和一些数学逻辑,我们学习了如何四舍五入到小数点后两位。我们还学习了如何使用 decimal 模块将给定的浮点数转换为小数并对其进行量化。