![](https://secure.gravatar.com/avatar/fd5ed3e385869d09fd4061e33e834a59.jpg?s=120&d=mm&r=g)
Hi all! When you work with numbers and need to print them, more often than not you want to round them. You can use the built-in round() function:
round(1.123, 2) 1.12 x = [1.123, 44.32, 12.11234] [round(x_i, 2) for x_i in x] [ 1.12, 44.32, 12.11]
However, when you want to round numbers in a more complex Python object, you need to be careful; you may also need to write a dedicated function to round numbers in this object, and you may need to update it if the object's structure changes. Now, you do not need to do that: use the rounder Python package instead. It will round numbers in any non-nested or nested Python object, using the following functions: * round_object(obj, digits), which rounds numbers in the object to a provided number of decimal digits * ceil_object(obj), which rounds numbers up to the nearest integer * floor_object(obj), which rounds numbers down to the nearest integer * signif_object(obj, digits), which rounds numbers to a number of significant digits So, for example:
obj = {'float': 1.345442, 'list': [1.1222, 1.1226, "string"], 'set': {1.1222, 1.1226}, 'tuple': (1.1222, 1.1226)} round_object(obj, 2) {'float': 1.35, 'list': [1.12, 1.12, "string"], 'set': {1.12}, 'tuple': (1.12, 1.12)} signif_object(obj, 3) {'float': 1.35, 'list': [1.12, 1.12, "string"], 'set': {1.12}, 'tuple': (1.12, 1.12)}
The package offers also two other functions: * signif(x, digits), to round a number to significant digits * map_object(map_function, obj, use_copy=False) The latter function is a generalized function that applies callable map_function to all numbers in obj. Consider this simplistic example:
map_object(lambda x: x**2, {'a': 3, 'b': [1, 2, 3]}) {'a': 9, 'b': [1, 4, 9]}
The package works with objects of many different types, not only those shown above. It works under both Windows and Linux. You can install it from PyPi: $ pip install rounder You will learn more about it from its GitHub repo: https://github.com/nyggus/rounder. Happy rounding! Pozdrawiam, Marcin