问题描述
我试图在Python中截断十进制值。我不想四舍五入,只是显示十进制值达到指定的精度。我试过以下内容: d = 0.989434
'{:。{prec} f}'。format(d ,prec = 2)
这个值为0.99。但我实际上希望输出是0.98。显然, round()
不是一个选项。有没有办法做到这一点?或者我应该回到代码并将所有内容更改为 decimal
?
谢谢。
我不知道所有的要求,但是这会相当健壮。 $ p> >> before_dec,after_dec = str(d).split('。')
>> float('。'。join((before_dec,after_dec [0:2])))
0.98
2018-01-03编辑
这个答案不健全或数学上正确。请参阅,了解正确的方法,使用 Decimal.quantize
方法。
I am trying to truncate a decimal value in Python. I don't want to round it, but instead just display the decimal values upto the specified accuracy. I tried the following:
d = 0.989434
'{:.{prec}f}'.format(d, prec=2)
This rounds it to 0.99. But I actually want the output to be 0.98. Obviously, round()
is not an option. Is there any way to do this? Or should I go back to the code and change everything to decimal
?
Thanks.
I am not aware of all your requirements, but this will be fairly robust.
>> before_dec, after_dec = str(d).split('.')
>> float('.'.join((before_dec, after_dec[0:2])))
0.98
2018-01-03 edit
This answer isn't robust or mathematically correct. See Nilani Algiriyage's answer below for the correct way to do this using Decimal.quantize
method.
这篇关于在Python中截断十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!