-5

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Hick
  • 35,524
  • 46
  • 151
  • 243

4 Answers4

3

Since this thread is first on the words "string formating decimal python", I think it's good to provide a more recent answer :

>>> P=34.3234564
>>> string="{:.2f}".format(P)
>>> string
'34.32'
1

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
  • 217,122
  • 57
  • 293
  • 297
1

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
  • 2,974
  • 2
  • 23
  • 24
0

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
  • 5,159
  • 5
  • 30
  • 40