How to print a float with underscores separating thousandths?

61 Views Asked by At

If possible, i want to format (via f-string or any older way) a float, so that it's thousandths get separated by underscores.

I know you can do:

print(f"{10000000:_}")
# 10_000_000

But i want:

print(f"{7.012345678:<something>}")
# 7.012_345_678
1

There are 1 best solutions below

1
John Coleman On

Hopefully someone has a better idea than I do, but if worse comes to worse you could do something like this:

def format_decimals(f):
    s = str(f)
    parts = s.split('.')
    if len(parts) != 2:
        raise ValueError(f'{s} not a valid decimal number')
    n,d = parts
    d = '_'.join(d[i:i+3] for i in range(0,len(d),3))
    return f'{n}.{d}'

import math
print(format_decimals(math.pi)) #3.141_592_653_589_793