Skip to content

Instantly share code, notes, and snippets.

@rudifa
Last active August 29, 2015 14:05
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 rudifa/ca4476e862da66e39ba2 to your computer and use it in GitHub Desktop.
Save rudifa/ca4476e862da66e39ba2 to your computer and use it in GitHub Desktop.
format_rounded.py
# formatter for arrays of floating point numbers
# Rudi Farkas 8 Aug 2014
def format_rounded(float_arr, decimals=2, general=False, sep=', '):
"""
Formats elements of float_arr with the stated number of decimal digits,
in the fixed '%f' or general '%g' format.
Returns the element strings joined with the separator.
"""
return sep.join(['{:.{precision}{type}}'.format(x, precision=decimals, type='g' if general else 'f') for x in float_arr])
if __name__ == '__main__':
import unittest
class T(unittest.TestCase):
def test_format_rounded_fixed_and_general(self):
arr1 = [i/3 for i in range(6)]
self.assertEqual(format_rounded(arr1, decimals=3), '0.000, 0.333, 0.667, 1.000, 1.333, 1.667')
self.assertEqual(format_rounded(arr1, decimals=3, general=True), '0, 0.333, 0.667, 1, 1.33, 1.67')
arr2 = [1/3/10**i for i in range(6)]
self.assertEqual(format_rounded(arr2, decimals=4, sep=' '), '0.3333 0.0333 0.0033 0.0003 0.0000 0.0000')
self.assertEqual(format_rounded(arr2, decimals=4, general=True), '0.3333, 0.03333, 0.003333, 0.0003333, 3.333e-05, 3.333e-06')
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment