在Python中截断十进制值 [英] Truncate a decimal value in Python

查看:208
本文介绍了在Python中截断十进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在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编辑



这个答案不健全或数学上正确。请参阅 Nilani Algiriyage的答案,了解正确的方法,使用 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中截断十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆