Beginner: Trying to get REAL NUMBERS from %d command

Peter Otten __peter__ at web.de
Mon Dec 31 00:09:18 CET 2012


Alvaro Lacerda wrote:

> The code I wrote is supposed to ask the user to enter a number;
> Then tell the user what's going to happen to that number (x / 2 + 5) ;
> Then give the user an answer;
> 
> I succeeded getting results from even numbers, but when I try diving an
> uneven number (i.e. 5) by 2, I get only the whole number (i.e. 2)
> 
> I'm trying to get full number result using the %d command, I've tried to
> add the line "from __future__ import division" to the beginning of my
> code, but I haven't been succeeded.
> 
> I also tried making my numbers decimals (i.e. 2.0 instead of just 2)
>  
> 
> Below is my program and thanks for the help :)
> 
> 
> 
> from __future__ import division;
> 
> def decimal_percent_test():
>     number = input("Enter a number: ");
>     print number, "will be divided by 2 then added by 5!";
>     print " %d divided by %d is %d plus %d is... %d !"
>     %(number,2,number/2,5,number/2+5);

Let's try it in the interactive interpreter:


>>> from __future__ import division
>>> 5/2
2.5

So the caculation part works.

>>> "%d" % 2.5
'2'

But the decimal part is dropped by the formatting operation. You have to use 
another format. The simplest is %s:

>>> "%s" % 2.5
'2.5'

%f is also possible and offers more control over the output:

>>> "%f" % 2.5
'2.500000'
>>> "%.2f" % 2.5
'2.50'

See <http://docs.python.org/2/library/stdtypes.html#string-formatting>
for more.




More information about the Python-list mailing list