float / rounding question

Mel mwilson at the-wire.com
Mon Feb 25 10:21:17 EST 2008


helen.m.flynn at gmail.com wrote:
> Hi I'm very much a beginner with Python.
> I want to write a function to convert celcius to fahrenheit like this
> one:
> 
> def celciusToFahrenheit(tc):
>     tf = (9/5)*tc+32
>     return tf
> 
> I want the answer correct to one decimal place, so
> celciusToFahrenheit(12) would return 53.6.
> 
> Of course the function above returns 53.600000000000001.
> 
> How do I format it correctly?

print celcisuToFahrenheit (12)

will do fine.


Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> def celciusToFahrenheit(tc):
...     tf = (float(9)/5)*tc+32
...     return tf
...
 >>> celciusToFahrenheit (12)
53.600000000000001
 >>> print celciusToFahrenheit (12)
53.6


The straight value display from the interpreter pursues precision to 
the bitter end, doing its formatting with the repr function.  print 
uses str formatting for a more expected result.

	Mel.




More information about the Python-list mailing list