前言
在Python中,保留小数点后特定位数可以通过多种方式实现
以下是几种常见的方法,并附上相应的代码示例:
- 使用字符串格式化(String Formatting)
- 使用round()函数
- 使用Decimal模块
- 使用numpy库
1. 字符串格式
方法1:使用f-strings (Python 3.6及以上)
1 2 3 | value = 3.141592653589793 formatted_value = f "{value:.2f}" print (formatted_value) # 输出: 3.14 |
方法2:使用str.format()
1 2 3 | value = 3.141592653589793 formatted_value = "{:.2f}" . format (value) print (formatted_value) # 输出: 3.14 |
方法3:使用百分号 (%) 格式化
1 2 3 | value = 3.141592653589793 formatted_value = "%.2f" % value print (formatted_value) # 输出: 3.14 |
2. round函数
1 2 3 | value = 3.141592653589793 rounded_value = round (value, 2 ) print (rounded_value) # 输出: 3.14 |
3. Decimal模块
Decimal模块提供更高的精度和控制,可以精确控制小数点后的位数
1 2 3 4 5 | from decimal import Decimal, ROUND_HALF_UP value = Decimal( '3.141592653589793' ) rounded_value = value.quantize(Decimal( '0.01' ), rounding = ROUND_HALF_UP) print (rounded_value) # 输出: 3.14 |
4. numpy库
大量的数值计算,使用numpy库是个好选择
1 2 3 4 5 | import numpy as np value = 3.141592653589793 rounded_value = np. round (value, 2 ) print (rounded_value) # 输出: 3.14 |
5. Demo
总体Demo如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import numpy as np from decimal import Decimal, ROUND_HALF_UP value = 3.141592653589793 # 使用f-strings formatted_value_f = f "{value:.2f}" print (f "f-strings: {formatted_value_f}" ) # 使用str.format() formatted_value_format = "{:.2f}" . format (value) print (f "str.format(): {formatted_value_format}" ) # 使用百分号 (%) 格式化 formatted_value_percent = "%.2f" % value print (f "百分号格式化: {formatted_value_percent}" ) # 使用round()函数 rounded_value_round = round (value, 2 ) print (f "round(): {rounded_value_round}" ) # 使用Decimal模块 decimal_value = Decimal( '3.141592653589793' ) rounded_value_decimal = decimal_value.quantize(Decimal( '0.01' ), rounding = ROUND_HALF_UP) print (f "Decimal模块: {rounded_value_decimal}" ) # 使用numpy库 rounded_value_numpy = np. round (value, 2 ) print (f "numpy库: {rounded_value_numpy}" ) |
截图如下:
到此这篇关于python保留小数点位数的多种方式(附demo)的文章就介绍到这了,更多相关python保留小数点位数内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!