String to Float, without introducing errors

Alan Gauld learn2program at gmail.com
Sat Dec 17 07:11:37 EST 2022


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