-2

I have problem in generating or getting decimal value in python. for now, I am using float(), but it returns .0 not .00 ...

>>> d = 10
>>> float(d)
10.0
>>> 

how can I set a decimal value that returns with .00?

>>10.00

thanks in advance ...

gadss
  • 21,687
  • 41
  • 104
  • 154

4 Answers4

8

Python only displays what's needed, so it displated 10.0

If it's the matter of printing it as 10.00.

To do that.

>>> d = 10
>>> print "Value: %.2f" % float(d)
Value: 10.00
>>> 
shadyabhi
  • 16,675
  • 26
  • 80
  • 131
  • @ Abhijeet, thanks for the reply... i try your answer but it returns into a string, i cannot do some mathematical activities... – gadss Feb 13 '12 at 09:46
  • @gadss `float(d)` already a float. I just printed it differently. Python only displayed what's needed in your case. It's actually a float only. You can continue on with your calculations without worrying about how many digits are after the decimal. – shadyabhi Feb 13 '12 at 09:48
  • ahh.. thanks Abhijeet Rastogi :) – gadss Feb 13 '12 at 09:56
3

You could also use format as follows:

>>> '{0:.2f}'.format(float(d))
10.00
jcollado
  • 39,419
  • 8
  • 102
  • 133
3

If you want your arithmetic to take into account how many digits after the period you should have, you must use the decimal module:

>>> from decimal import Decimal
>>> Decimal("10.0")
Decimal('10.0')
>>> Decimal("10.00")
Decimal('10.00')
>>> Decimal("10.0")**2
Decimal('100.00')
>>> Decimal("10.00")**2
Decimal('100.0000')

I guess I also should mention the python uncertainties module:

>>> from uncertainties import ufloat
>>> x = ufloat((2, 0.25))
>>> x
2.0+/-0.25
>>> square = x**2  # Transparent calculations
>>> square
4.0+/-1.0
Lauritz V. Thaulow
  • 49,139
  • 12
  • 73
  • 92
0

Python is displaying 10.0 because you're displaying a floating point number, and Python will only display as many decimal places as is needed.

If you want to print 10.00 for display purposes, use the string formatting operator % like so:

>>> a = 10
>>> float (a)
10.0
>>> "%2.2f" % a
'10.00'
>>> 

More about string formatting operations.

Li-aung Yip
  • 12,320
  • 5
  • 34
  • 49