Python print a float with a given number of digits

16,522

Solution 1

Ok I thought about this solution that is basically a work-around:

LIM = 7;
a = 12.123456
b = 123.1234567
print(str(a)[:LIM])
print(str(b)[:LIM])

Solution 2

The formating method for both integer and decimal is

>>> '{:06.2f}'.format(3.141592653589793)
'003.14'

the part before the . (6 here) denotes the total length of padding (including the .), and after the . (2fhere) denotes digits after decimal point. Hope it helps. checkout the link.

Solution 3

You can try to do something like this

print('{:.6}'.format(val))
Share:
16,522
Francesco Boi
Author by

Francesco Boi

Interested in programming, electronic, math, physics and technology. In my free-time I like playing sports, going to the sea, watching movies and reading.

Updated on June 05, 2022

Comments

  • Francesco Boi
    Francesco Boi almost 2 years

    I have some floating point values in Python. I would like to print them so that the have the same number of digits (sum of the integer and decimal parts)

    For example considering the two numbers:

    a = 12.123456
    b = 123.1234567
    

    I would like to print their value formatted as follows:

    12.1234
    123.123
    

    So that they have the same length.

    One simple way is the following:

    if (val>100):
        print("%0.3f" % val)
    else:
        print("%0.4f" % val)
    

    Is there a smarter way to control both the number of integer and decimal digits at the same time in python so that the resulting string is constant?

  • Francesco Boi
    Francesco Boi almost 6 years
    Actually it works in most of the cases but not if the integer part is 0: for example it does not work in the case of 0.678923156 because it prints 6 decimals without counting the 0 integer part
  • Admin
    Admin almost 6 years
    it looks a bit scary, but will work for the case with zero at the beginning print(('{:.6}' if int(val) else '{:.5}').format(val)) {:.5} - this will applied if integer part equals zero, in other cases {:.6}