python - Create compact/human-friendly floats using unicode vulgar fractions -


are there modules (preferably in standard library), can turn float number more human friendly? maybe it's not more human friendly, @ least more compact.

eg. 4.625 become "4⅝"

(bonus brownie points recognizing pi reasonable precision)

this code outline best come with:

import unicodedata  def simplify_float(number):     vf = "vulgar fraction "     vulgars = {0.125 : unicodedata.lookup(vf + "one eighth"),                0.2   : unicodedata.lookup(vf + "one fifth"),                0.25  : unicodedata.lookup(vf + "one quarter"),                0.375 : unicodedata.lookup(vf + "three eighths"),                0.4   : unicodedata.lookup(vf + "two fifths"),                0.5   : unicodedata.lookup(vf + "one half"),                0.6   : unicodedata.lookup(vf + "three fifths"),                0.625 : unicodedata.lookup(vf + "five eighths"),                0.75  : unicodedata.lookup(vf + "three quarters"),                0.8   : unicodedata.lookup(vf + "four fifths"),                0.875 : unicodedata.lookup(vf + "seven eighths")}      decimal = int(number)     if number == decimal:         return unicode(decimal)      vulgar = vulgars.get(number - decimal)     if vulgar:         if decimal == 0:             return vulgar         return "%d%s" % (decimal, vulgar)     return "%.1f" % number 

going other direction pretty easy using unicodedata module, couldn't find way author these strings in first place.

there only twenty of these fraction forms in unicode. unlikely there ever more (as exist backwards compatibility other character sets), hardcoding them robust enough.

the general way of encoding fractions use u+2044 fraction slash. font shaping/layout engines allowed render numbers fraction slash (e.g., 1⁄2) slanted or stacked fraction (e.g., ½)—however, have not encountered (and plain rendering 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 best way handle precision (e.g., 1/3) depend on format numbers exist in , how error acceptable.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -