limited float decimal point without rounding the number [duplicate]

ε祈祈猫儿з 提交于 2020-03-20 17:51:04

问题


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)

This code return this number:

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.


回答1:


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.

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

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)

Outputs:

3.100



回答2:


try str and slicing

a = 12.341661
b = str(int(a))
c = str(a - int(a))[1:5]
d = b + c
print(d)


来源:https://stackoverflow.com/questions/52997663/limited-float-decimal-point-without-rounding-the-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!