Formatting Long Numbers as Strings in Python

Formatting long numbers as strings

I don't think there's a built-in function that does that. You'll have to roll your own, e.g.:

def human_format(num):
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
# add more suffixes if you need them
return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])

print('the answer is %s' % human_format(7436313)) # prints 'the answer is 7.44M'

Format numbers to strings in Python

Starting with Python 3.6, formatting in Python can be done using formatted string literals or f-strings:

hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'

or the str.format function starting with 2.7:

"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")

or the string formatting % operator for even older versions of Python, but see the note in the docs:

"%02d:%02d:%02d" % (hours, minutes, seconds)

And for your specific case of formatting time, there’s time.strftime:

import time

t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%S %p', t)

python human readable large numbers

As I understand it, you only want the 'most significant' part. To do so, use floor(log10(abs(n))) to get number of digits and then go from there. Something like this, maybe:

import math

millnames = ['',' Thousand',' Million',' Billion',' Trillion']

def millify(n):
n = float(n)
millidx = max(0,min(len(millnames)-1,
int(math.floor(0 if n == 0 else math.log10(abs(n))/3))))

return '{:.0f}{}'.format(n / 10**(3 * millidx), millnames[millidx])

Running the above function for a bunch of different numbers:

for n in (1.23456789 * 10**r for r in range(-2, 19, 1)):
print('%20.1f: %20s' % (n,millify(n)))
0.0: 0
0.1: 0
1.2: 1
12.3: 12
123.5: 123
1234.6: 1 Thousand
12345.7: 12 Thousand
123456.8: 123 Thousand
1234567.9: 1 Million
12345678.9: 12 Million
123456789.0: 123 Million
1234567890.0: 1 Billion
12345678900.0: 12 Billion
123456789000.0: 123 Billion
1234567890000.0: 1 Trillion
12345678900000.0: 12 Trillion
123456789000000.0: 123 Trillion
1234567890000000.0: 1235 Trillion
12345678899999998.0: 12346 Trillion
123456788999999984.0: 123457 Trillion
1234567890000000000.0: 1234568 Trillion

How to format a floating number to fixed width in Python

numbers = [23.23, 0.1233, 1.0, 4.223, 9887.2]                                                                                                                                                   

for x in numbers:
print("{:10.4f}".format(x))

prints

   23.2300
0.1233
1.0000
4.2230
9887.2000

The format specifier inside the curly braces follows the Python format string syntax. Specifically, in this case, it consists of the following parts:

  • The empty string before the colon means "take the next provided argument to format()" – in this case the x as the only argument.
  • The 10.4f part after the colon is the format specification.
  • The f denotes fixed-point notation.
  • The 10 is the total width of the field being printed, lefted-padded by spaces.
  • The 4 is the number of digits after the decimal point.

Quickly formatting numbers in print() calls with tuples mixing strings and numbers

from typing import Any

def standarize(value: Any) -> str:
if type(value) == int:
return str(value)
elif type(value) == float:
return f'{value:.2f}'
else:
return str(value)

print(f'Value int: {standarize(1)}')
print(f'Value float: {standarize(113.91715)}')
print(f'Value str: {standarize("any string")}')

How to format very small numbers in python?

The "g" formatting suffix on string mini-format language, used both by f-strings, and the .format method will do that:

In [1]: a = 1.34434325435e-8

In [2]: a
Out[2]: 1.34434325435e-08

In [4]: f"{a:.03g}"
Out[4]: '1.34e-08'

# in contrast with:
In [5]: f"{a:.03f}"
Out[5]: '0.000'

Best way to format integer as string with leading zeros?

You can use the zfill() method to pad a string with zeros:

In [3]: str(1).zfill(2)
Out[3]: '01'


Related Topics



Leave a reply



Submit