Home >Backend Development >Python Tutorial >How to Convert Strings to Floats and Integers in Python?

How to Convert Strings to Floats and Integers in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 14:46:10751browse

How to Convert Strings to Floats and Integers in Python?

Parsing Strings to Floats and Integers in Python

Converting strings to numeric data types is a common task in programming. Python provides built-in functions that effortlessly perform these conversions.

Converting Strings to Floats

To parse a string into a floating-point number, use the float() function. For example:

>>> a = "545.2222"
>>> float(a)
545.22220000000004 # Note the precision loss

The float() function attempts to convert the entire string to a float. If it encounters non-numeric characters, a ValueError is raised.

Converting Strings to Integers

To parse a string into an integer, use the int() function. However, this function by default converts the entire string to an integer, which may not be desired in all cases.

>>> b = "31"
>>> int(b)
31

If you wish to convert only the numeric portion of a string, you can first convert it to a float and then truncate it to an integer:

>>> c = ">>> a = "31.6666""
>>> int(float(c))
31

This approach ensures that the fractional part of the number is discarded, leaving only the integer value.

The above is the detailed content of How to Convert Strings to Floats and Integers in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn