tags:

views:

208

answers:

3

my input is 3.23 , but when i use float on it , it becomes 3.2 ,

when my input is 3.00 , when i do float on it , it becomes 3.0

when i convert to float from string , i still want it to be 3.00 and not 3.0 is it possible? i want to know the code to make it possible , and when i am doing a problem in which the decimal point till 2 digits matter, 3.23 is better than 3.2 , for more precision

+1  A: 

if you want decimal precision use the python decimal module:

from decimal import Decimal
x = Decimal('3.00')
print x

That prints:

Decimal('3.00')
nosklo
A: 

If you want to print a floating-point number to a desired precision you can use output formatting codes like the following:

Assuming x = 3.125

print "%.1f" % (x)    # prints 3.1
print "%.2f" % (x)    # prints 3.12
print "%.3f" % (x)    # prints 3.125
print "%.4f" % (x)    # prints 3.1250

This will work in python 2.6 (I think they changed the print function in version 3).

You should also realize that floating-point numbers can only be stored with a certain accuracy, so sometimes you will not get the exact same number back. For example 0.1 may be stored as something like 0.9999999987.

MahlerFive
+1  A: 

I suppose that what you want is to convert a float to a string with the number of decimals that you want. You can achieve that using %.3f (here 3 is the number of decimals that you want to print. For example:

>>> print "Value: %.2f" % 3.0000

Value: 3.00

Artur Soler