float problem

Mike C. Fletcher mcfletch at rogers.com
Thu Mar 18 05:46:50 EST 2004


Tomasz Stochmal wrote:

>Hi
>
>
>I need to write a function that will convert a float number given as
>string into long and reverse function of that, example:
>
>'713566671863.6850' becomes 7135666718636850L
>7135666718636850L becomes '713566671863.6850'
>  
>
This really sounds like something you should do with fixedpoint, but if 
for some reason you can't use that and you want a quick hack:

 >>> def toLong( source ):
...     try:
...         whole, fraction = source.split( '.', 1 )
...     except ValueError: # no .
...         whole, fraction = source, ''
...     fraction = fraction[:4] +  '0000'[len(fraction):]
...     return long( whole + fraction )
...
 >>> toLong( '713566671863' )
7135666718630000L
 >>> toLong( '713566671863.6850' )
7135666718636850L
 >>> toLong( '.23' )
2300L
 >>>

But really, look at fixedpoint.py, likely to be far closer to what you 
*really* want.

HTH,
Mike

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/






More information about the Python-list mailing list