我知道如何在小数点后只保留两位小数。例如(还有其他方法):
>>> print(f'{10000.01908223295211791992:.2f}')
10000.02
但是我想保留小数点后除零之外的前两位数字:
10000.01908223295211791992 将给出:10000.019
0.0000456576578765 将给出:0.000046
是否有我缺少的内置方法?或者是为(几乎)每种情况编写测试代码的唯一解决方案?
这段代码可以按照你想要的方式工作,我定义了一个函数,因为在执行此舍入操作时存在一些异常:
import decimal
# Set the precision of the decimal module to 20, it should be more than enough
ctx = decimal.Context()
ctx.prec = 20
# utility function to convert float to string
def float_to_str(f):
d1 = ctx.create_decimal(repr(f))
return format(d1, 'f')
def format_first_two_non_zero_digits(number):
number_str = float_to_str(number) # Convert the number to a string
decimal_point_index = number_str.find('.') # Find the position of the decimal point
# If there is no decimal point, return the original number
if decimal_point_index == -1:
return number_str
# Iterate through the digits after the decimal point
for i in range(decimal_point_index + 1, len(number_str)):
if number_str[i] != '0':
# Found the first non-zero digit after the decimal point
return number_str[:i + 2]
return number_str # If all digits after the decimal point are zero, return the original number
# Examples
number1 = 10000.01908223295211791992
number2 = 0.0000456576578765
formatted1 = format_first_two_non_zero_digits(number1)
formatted2 = format_first_two_non_zero_digits(number2)
print(formatted1)
print(formatted2)
Marco 的答案当然是有效的,但我认为当可以用正则表达式解决这个问题时,它有点重新发明轮子:
import re
def rounder(number):
pattern = re.compile(r'(\d+\.(([1-9]*)?|0+)0[1-9]{2})') #one or more numbers, a decimal point, then either any number of non-0s, or one or more zeros, followed by a zero and 2 other numbers
if result:=pattern.match(str(number)):
return(float(result.group(1)))
else:
return(None)
如果正则表达式不匹配,它将简单地返回
None
——如果您需要错误处理,您可以调整它。