1

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..>?

tejosa
  • 135
  • 2
  • 11

2 Answers2

6

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.

iGian
  • 11,023
  • 3
  • 21
  • 36
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.

J_Zoio
  • 338
  • 1
  • 3
  • 16