[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

round() function

Tracubik

2/25/2010 3:40:00 PM

hi all, i've this sample code:

>>> n = 4.499
>>> str(round(n,2))
'4.5'

that's right, but what i want is '4.50' to be displayed instead of '4.5'.
Off course i know that 4.5 = 4.50, still i'ld like to have 4.50.

How can I solve this?

Thanks in advance
Nico
4 Answers

Tim Chase

2/25/2010 3:45:00 PM

0

Tracubik wrote:
>>>> n = 4.499
>>>> str(round(n,2))
> '4.5'
>
> that's right, but what i want is '4.50' to be displayed instead of '4.5'.
> Off course i know that 4.5 = 4.50, still i'ld like to have 4.50.

Use string formatting:

>>> "%0.2f" % round(4.499, 2)
'4.50'

-tkc



mailing list

2/25/2010 3:46:00 PM

0

On 25.2.2010. 16:39, Tracubik wrote:
> hi all, i've this sample code:
>
>
>>>> n = 4.499
>>>> str(round(n,2))
>>>>
> '4.5'
>
> that's right, but what i want is '4.50' to be displayed instead of '4.5'.
> Off course i know that 4.5 = 4.50, still i'ld like to have 4.50.
>
> How can I solve this?
>
> Thanks in advance
> Nico
>
You may wanna use string formating, e.g.: print "%.2f" % 4.5

Stefan Behnel

2/25/2010 3:46:00 PM

0

Tracubik, 25.02.2010 16:39:
> hi all, i've this sample code:
>
>>>> n = 4.499
>>>> str(round(n,2))
> '4.5'
>
> that's right, but what i want is '4.50' to be displayed instead of '4.5'.
> Off course i know that 4.5 = 4.50, still i'ld like to have 4.50.
>
> How can I solve this?

Format the number as a string:

print("%.2f" % round(n,2))

Stefan

Michael Rudolf

2/25/2010 3:52:00 PM

0

Am 25.02.2010 16:39, schrieb Tracubik:
> hi all, i've this sample code:
>
>>>> n = 4.499
>>>> str(round(n,2))
> '4.5'
>
> that's right, but what i want is '4.50' to be displayed instead of '4.5'.
> Off course i know that 4.5 = 4.50, still i'ld like to have 4.50.
>
> How can I solve this?
>
> Thanks in advance
> Nico

This has nothing to do with round().
round() returns a float, and float(4.50) is 4.5.

You can *print* it as 4.50 using format strings, but the float will
always be 4.5


>>> n = 4.499
>>> x=round(n,2)
>>> x
4.5
>>> print "%.2f" % x
4.50
>>> s="%.2f" % round(n,2)
>>> s
'4.50'
>>>