Formatting Numbers So They Align On Decimal Point
If you know the precision (digits after the decimal point) that you need, and you don't mind having some trailing zeros when whole numbers are used, you could use the new f-string
in Python 3.6 (PEP498):
numbers = [4.8, 49.723, 456.781, -72.18, 5, 13]
for number in numbers:
print(f'{number:9.4f}')
Prints:
4.8000
49.7230
456.7810
-72.1800
5.0000
13.0000
I don't think there's a straight-forward way to do it, since you need to know the position of the decimal point in all the numbers before you start printing them. (I just had a look at Caramiriel's link, and some of the links from that page, but I couldn't find anything particularly applicable to this case).
So it looks like you have to do some string-based inspection & manipulation of the numbers in the list. Eg,
def dot_aligned(seq):
snums = [str(n) for n in seq]
dots = [s.find('.') for s in snums]
m = max(dots)
return [' '*(m - d) + s for s, d in zip(snums, dots)]
nums = [4.8, 49.723, 456.781, -72.18]
for s in dot_aligned(nums):
print(s)
output
4.8
49.723
456.781
-72.18
If you want to handle a list of float
s with some plain int
s mixed in, then this approach gets a bit messier.
def dot_aligned(seq):
snums = [str(n) for n in seq]
dots = []
for s in snums:
p = s.find('.')
if p == -1:
p = len(s)
dots.append(p)
m = max(dots)
return [' '*(m - d) + s for s, d in zip(snums, dots)]
nums = [4.8, 49.723, 456.781, -72.18, 5, 13]
for s in dot_aligned(nums):
print(s)
output
4.8
49.723
456.781
-72.18
5
13
update
As Mark Ransom notes in the comments, we can simplify handling int
s by using .split
:
def dot_aligned(seq):
snums = [str(n) for n in seq]
dots = [len(s.split('.', 1)[0]) for s in snums]
m = max(dots)
return [' '*(m - d) + s for s, d in zip(snums, dots)]
Here's how I did it!
def alignDots(number):
try:
whole, dec = str(number).split('.')
numWholeSpaces = 5 - len(whole) # Where 5 is number of spaces you want to theleft
numDecSpaces = 3 - len(dec) # 3 is number of spaces to the right of the dot
thousands = ' '* Math.abs(numWholeSpaces) + whole
decimals = dec + '0'*Math.abs(numDecSpaces)
print thousands + '.' + decimals
return thousands + '.' + decimals
except:
print "Failed to align dots of ",number
return ' '*5+'ERROR'
I like the other solutions, but needed something specific and thought why not share!