How to get specific number of digits? Python

时间:2019-01-09 21:56:34

标签: python floating-point

How would I format my float digits so that there is always 7 digits no matter the direction?

The value could be any of the following but I always want 7 like below

0.0054233
1234567
123.1224
1.992923

The portion I have right now is

return "%.7f" % fd

How can I adjust that to get my desired output? or maybe link me to something similar I could try and read from..>?

2 个答案:

答案 0 :(得分:4)

Try if this can work for you:

n = 123.456789
decimals = 7 - len(str(int(n)))
print('{:.{prec}f}'.format(n, prec=decimals))
#=> 123.4568

The drawback is that it rounds up.

答案 1 :(得分:1)

It depends on the context of the program, in my opinion... If you just want the numbers to the right to be 6 decimals, use:

"{:.6f}".format(whatevervar)

In other contexts maybe convert it to a string and use len() to evaluate the number of digits.

Hope this helps!

EDIT: Seeing your comments, I would recommend using a conditional to define what you are trying to do. When the number has no decimals (check this thread for how to do it: How to check if a float value is a whole number ) leave it as it is, when it has decimals, round it up with the code I posted above.