String to Float, without introducing errors

Paul St George email at paulstgeorge.com
Sat Dec 17 15:45:06 EST 2022


Thanks to all!
It was the rounding rounding error that I needed to avoid (as Peter J. Holzer suggested). The use of decimal solved it and just in time. I was about to truncate the number, get each of the characters from the string mantissa, and then do something like this:

64550.727

64550 + (7 * 0.1) + (2 * 0.01) + (7 * 0.001)

Now I do not need to!





> On 17 Dec 2022, at 13:11, Alan Gauld <learn2program at gmail.com> wrote:
> 
> On 17/12/2022 11:51, Paul St George wrote:
>> I have a large/long array of numbers in an external file. The numbers look like this:
>> 
>> -64550.727
>> -64511.489
>> -64393.637
>> -64196.763
>> -63920.2
> 
>> When I bring the numbers into my code, they are Strings. To use the 
>> numbers in my code, I want to change the Strings to Float type 
>> because the code will not work with Strings but I do not want 
>> to change the numbers in any other way.
> 
> That may be impossible. Float type is not exact and the conversion
> will be the closest binary representation of your decimal number.
> It will be very close but it may be slightly different when you
> print it, for example. (You can usually deal with that by using
> string formatting features.)
> 
> Another option is to use the decimal numeric type. That has other
> compromises associated with it but, if retaining absolute decimal
> accuracy is your primary goal, it might suit you better.
> 
> 
> -- 
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
> 
> 



More information about the Python-list mailing list