有限的浮点小数点,不四舍五入 [英] limited float decimal point without rounding the number

查看:102
本文介绍了有限的浮点小数点,不四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数字转换为带小数点后3位的浮点数,但我不希望取整. 例如:

I want convert a number to a float number with 3 decimal point but I want it without rounding. For example:

a = 12.341661
print("%.3f" % a)

此代码返回该数字:

12.342

但是我需要原始号码,我需要这个:

but I need to original number,I need this:

12.341

我编写了一个接收数字形式用户的代码,并将其转换为浮点数. 我不知道与用户输入的号码是什么.

I write a code that receive a number form user and convert it to a float number. I have no idea that what is the number entered with user.

推荐答案

我的第一个念头是将print("%.3f" % a)更改为print("%.3f" % (a-0.0005)),但效果不佳:当输出a = 12.341661时,如果= 12.341则输出12.340,这显然是不正确的.

My first thought was to change print("%.3f" % a) to print("%.3f" % (a-0.0005)) but it does not quite work: while it outputs what you want for a=12.341661, if a=12.341 it outputs 12.340, which is obviously not right.

相反,我建议使用int()明确地进行铺地板:

Instead, I suggest doing the flooring explicitly using int():

a = 12.341661
b = int(a*1000)/1000.
print(b)

这将输出您想要的内容:

This outputs what you want:

12.341

要获得3个小数,即使输入较少,也可以设置输出格式:

To get 3 decimals out even if the input has fewer, you can format the output:

a = 3.1
b = int(a*1000)/1000.
print("%.3f" % b)

输出:

3.100

这篇关于有限的浮点小数点,不四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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