Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string to a double in Python?

People also ask

How do you declare a double in Python?

Python double star operatorDouble Star or (**) is an inbuilt Python Arithmetic Operator (Like +, -, *, **, /, //, %). For numeric data types, double-asterisk (**) is defined as an Exponentiation Operator.

How do you print double in Python?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number.

How do you convert a string to a decimal with two decimal places in Python?

Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.


>>> x = "2342.34"
>>> float(x)
2342.3400000000001

There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).


The decimal operator might be more in line with what you are looking for:

>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434

Be aware that if your string number contains more than 15 significant digits float(s) will round it.In those cases it is better to use Decimal

Here is an explanation and some code samples: https://docs.python.org/3/library/sys.html#sys.float_info