String to Float, without introducing errors

Peter J. Holzer hjp-python at hjp.at
Sat Dec 17 07:39:56 EST 2022


On 2022-12-17 12:51:17 +0100, 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
[...]
> 
> 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.

>>> s = "-64550.727"
>>> f = float(s)
>>> f
-64550.727
>>> type(f)
<class 'float'>

(Contrary to the other people posting in this thread I don't think float
is the wrong type for the job. It might be, but you haven't given enough
details to tell whether the inevitable rounding error matters or not. In
my experience in almost all cases where people think it matters it
really doesn't.)

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20221217/897cd017/attachment.sig>


More information about the Python-list mailing list