Entry
Decimal precision (rounding)
Jul 5th, 2000 10:00
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 139, David Ascher
"""
Packages: maths
"""
"""
> I was wondering if anyone knows how to limit decimal precision in
> Python. Here is an example of where my problem occurs:
>
> >>> 3.0 / 7
> 0.428571428571
>
> Lets say I wanted to limit the value it returns to 3 decimal places, for
> example. How would that be done?
One of the most under-appreciated builtins does a good job at it:
"""
print round(3.0/7, 3)
# 0.429
print round(3.0/7, 5)
# 0.42857
print round(3.0/7, 1)
# 0.4
print round(3.0/7, 2)
# 0.43