Skip to content

Instantly share code, notes, and snippets.

@bnlucas
Last active August 29, 2015 14:22
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 bnlucas/798404302b20606c1101 to your computer and use it in GitHub Desktop.
Save bnlucas/798404302b20606c1101 to your computer and use it in GitHub Desktop.
A better way to print formatted floats using the `format()` specs.
def float_spec(fill, align, sign, width, separator, precision):
if len(fill) > 1:
raise ValueError('The fill character can only contain 1 character.')
if align not in ['left', 'right', 'center', 'padded']:
raise ValueError('{} is not an allowed alignment.'.format(align))
if sign not in ['+', '-', ' ']:
raise ValueError('{} is not a valid sign.'.format(sign))
if width < 0:
raise ValueError('Width must be 0 or greater.')
if precision < 0:
raise ValueError('Precision must be 0 or greater.')
# if there will be no padding, width=0, omit fill, align, and width from
# the generated format spec.
if width == 0:
fill = ''
align = 'blank'
width = ''
align_spec = {
'left': '<',
'right': '>',
'center': '^',
'padded': '=',
'blank': ''
}
separator = ',' if separator is True else ''
return '{{:{0}{1}{2}{3}{4}.{5}f}}'.format(
fill,
align_spec[align],
sign,
width,
separator,
precision
)
def pretty_float(x, precision, width, fill, align, sign, separator):
out = float_spec(fill, align, sign, width, separator, precision)
return out.format(x)
def float_ljust(x, precision, width, fill=' ', separator=True, sign=' '):
return pretty_float(x, precision, width, fill, align='left', sign=sign,
separator=separator)
def float_rjust(x, precision, width, fill=' ', separator=True, sign=' '):
return pretty_float(x, precision, width, fill, align='right', sign=sign,
separator=separator)
def float_center(x, precision, width, fill=' ', separator=True, sign=' '):
return pretty_float(x, precision, width, fill, align='center', sign=sign,
separator=separator)
def float_padded(x, precision, width, fill=' ', separator=True, sign=' '):
return pretty_float(x, precision, width, fill, align='padded', sign=sign,
separator=separator)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment