我很难处理浮点数,而且我什至发现Python中的内置十进制类有时也很令人困惑。作为解决方案,我自己编写了一个方法,该方法只接受一个值和一些数字,这些数字应在浮点数之后显示,并以一种不错的格式返回字符串。看起来像这样:
def format_to_decimal_string(value, decimal_places):
"""
# Given the `value` and `decimal_places`, this method returns a string
in the format of a decimal number. Eg: `format_to_decimal_string('99.99', 1)`
returns '99.9', while `format_to_decimal_string('99.99', 0)` return '99'.
# The arguments are validated, to make sure `value` can be turned into
a decimal number, and `decimal_places` is an integer greater than 0.
The `value` is first turned into a string to accomodate for edge-cases,
such as `format_to_decimal_string(99.99, 2)`.
# If `decimal_number` is zero, we return a formatted zero string.
# The start index is calculated, and using that, we append numbers
to the string. Once again, we make sure to add zeroes to the start
and/or the end if needed.
# Finally, we append the minus sign if needed, and return the result.
"""
# Validating arguments
try:
decimal_number = decimal.Decimal(str(value)).as_tuple()
except:
raise ValueError('The value is not a valid decimal number.')
if not isinstance(decimal_places, int):
raise ValueError('The given decimal places is not an integer.')
if not decimal_places >= 0:
raise ValueError('The given decimal places must be greater than or equal to zero.')
# Check if `decimal_number` is zero
if decimal_number == 0:
result = '0'
if not decimal_places == 0:
result += '.'
for i in range(decimal_places):
result += '0'
return result
# Finding the start index
exponent_start_index = len(decimal_number.digits) + decimal_number.exponent
# Appending the first digit
if exponent_start_index == 0:
result = '0'
else:
result = ''
for digit in decimal_number.digits[0:exponent_start_index]:
result += str(digit)
# Appending the exponents
exponent = ''
if not decimal_places == 0:
result += '.'
for digit in decimal_number.digits[exponent_start_index:(decimal_places + exponent_start_index)]:
exponent += str(digit)
# Adding extra zeroes to make the number have a valid precision
if decimal_places > len(exponent):
for i in range(decimal_places - len(exponent)):
exponent += '0'
# Combining the first digit and the exponents
result = result + exponent
# Appending the minus sign if needed
if decimal_number.sign == 1:
if not decimal.Decimal(result) == 0:
result = '-' + result
return result
不言自明。它也考虑了零,只是为了使输出看起来不错。但是,我完全忘记的一件事是对数字进行取整。例如,当我希望它返回format_to_decimal_string(19.2189, 3)
时,'19.218'
返回'19.219'
。有了这么大的方法,我觉得没有简单的方法可以对此进行添加?我是否应该尝试用另一种解决方法重写新方法,或者将其合并到现有方法中?谢谢。
答案 0 :(得分:1)
如果要对此使用小数模块,则可以执行以下操作:
decimal.Decimal(19.2189).quantize(decimal.Decimal(10) ** -3)
quantize方法会将小数点四舍五入到其参数中的小数位数(因此您可以传递.001
而不是将小数点提高到-3)。
答案 1 :(得分:0)
{this.props.posts.slice(...
您可以使用round()
完成此操作。
round()
如果要将此数字转换为字符串:
>>> round(19.2189, 3)
19.219
>>> str(round(19.2189, 3))
'19.219'
您也可以使用format()
完成此操作:
format()