Are there any modules (preferably in the standard library), that can turn a float number into something the is more human friendly? Maybe it\'s not more human friendly, but
There are only twenty of these fraction forms in Unicode. It is unlikely that there will ever be more (as they only exist for backwards compatibility with other character sets), so hardcoding them is probably robust enough.
The general way of encoding fractions is to use ⁄
U+2044 FRACTION SLASH. Font shaping/layout engines are allowed to render numbers with a fraction slash (e.g., 1⁄2) with as a slanted or stacked fraction (e.g., ½)—however, I have not encountered any that do (and even the plain rendering is unfortunately quite ugly).
import math
import fractions
VULGAR_FRACTIONS = {(5, 8) : '\u215D', ...}
def compact_float(number):
parts = math.modf(number)
fraction = fractions.Fraction(parts[0])
simple = (fraction.numerator, fraction.denominator)
form = VULGAR_FRACTIONS.get(simple)
return '%i%s' % (parts[1], form) if form else str(number)
It's not clear what the best way is to handle precision (e.g., 1/3
) as it will depend on the format your numbers exist in and how much error is acceptable.