views:

44

answers:

3

Hi, I am using:

from __future__ import division

To perform a division in which I need some percision. However, it gives a long number, like:

1.876543820098765

I only need the the first two numbers after "." => 1.87 How can I do that?

A: 
f = 1.876543820098765
print f
print round(f, 2)

>> 1.8765438201
>> 1.88
van
+1  A: 
"%0.2f" % yournumber

As you said you don't want a rounded number, you might want to try

def twoDigits(x):
    return int(100*x)/100.0
jellybean
+1  A: 

The number are stored as binary floating point. If you need to show just two digits, you can turn the float into a string and control the number of digits displayed using printf like syntax.

mystring = "%.2f" % (x/y)

This will limit the string to have only 2 digits after the decimal point.

if x/y = 1.876543820098765
mystring = "1.88"

George Steel
Rounded => not what he wants
jellybean