String to Float, without introducing errors

Thomas Passin list1 at tompassin.net
Sat Dec 17 16:54:05 EST 2022


On 12/17/2022 3:45 PM, Paul St George wrote:
> 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!

And that approach would not have helped you, because each of those 
calculations would be done as floating point, and you wouldn't have 
gotten any more precision (and maybe less) than simply doing 
float('64550.727').

Here is a small but interesting discussion thread about float vs Decimal:

https://stackoverflow.com/questions/32053647/comparing-python-decimals-created-from-float-and-string

Would you mind telling us why that degree of precision (that is, decimal 
vs float) matters for your problem?


>> 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