How to round a floating point number?

It's another problem I faced few days ago. I needed to round a floating point number to two digits after decimal place. Then I found a function named 'round()'. Look at the following code block written in Python:


d = 10.0 / 3
print d
d = round(d, 2)
print d

Comments

Matt said…
You could also try:

print "$%.2f" % float(d)
Unknown said…
does not work for 0.12305944
hidechron said…
str(round(x))

maybe.
Shadda said…
Not to be a party pooper, I mean, I love python and all, but aren't we getting a little excited over a standard math function? I can't really think of a single language that doesn't have a native rounding function. Maybe mircscript.
sonych said…
Precision can be negative:
a = 321
round(a, -1)
>> 320

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code