Skip to content

Instantly share code, notes, and snippets.

@np1
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save np1/23992d61109f69331297 to your computer and use it in GitHub Desktop.
Save np1/23992d61109f69331297 to your computer and use it in GitHub Desktop.
String representation of large numbers in Python
import math
def num_repr(num):
""" Return up to four digit string representation of a number, eg 2.6m """
if num <= 9999:
return str(num)
digits = int(math.floor(math.log10(num)) + 1)
sig = 3 if digits % 3 == 0 else 2
rounded = int(round(num, int(sig - digits)))
digits = int(math.floor(math.log10(rounded)) + 1)
suffix = "_kmBTqXXX"[(digits - 1) // 3]
front = 3 if digits % 3 == 0 else digits % 3
if not front == 1:
return str(rounded)[0:front] + suffix
if str(rounded)[1] == "0":
return str(rounded)[0] + suffix
return str(rounded)[0] + "." + str(rounded)[1] + suffix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment