faqts : Computers : Programming : Languages : Python : Snippets : Maths

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

18 of 25 people (72%) answered Yes
Recently 4 of 10 people (40%) answered Yes

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