Last active
August 29, 2015 14:00
-
-
Save np1/23992d61109f69331297 to your computer and use it in GitHub Desktop.
String representation of large numbers in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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