Similar posts such as the following do not answer my question. Convert a string to integer with decimal in Python
Consider the following Python code.
>>> import decimal
>>> s = '23.456'
>>> d = decimal.Decimal(s)
>>> d
Decimal('23.456') # How do I represent this as simply 23.456?
>>> d - 1
22 # How do I obtain the output to be 22.456?
How do I convert a string to a decimal number, so I am able to perform arithmetic functions on it and obtain an output with the correct precision?
If you want to stay in decimal
numbers, safest is to convert everything:
>>> s = '23.456'
>>> d = decimal.Decimal(s)
>>> d - decimal.Decimal('1')
Decimal('22.456')
>>> d - decimal.Decimal('1.0')
Decimal('22.456')
In Python 2.7, there's an implicit conversion for integers, but not floats.
>>> d - 1
Decimal('22.456')
>>> d - 1.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'Decimal' and 'float'
Is the Decimal
required for your computations? The Decimal fixed point and floating point arithmetic doc outlines their differences. If not, you could just do
d = float('23.456')
d
23.456
d - 1
22.456
Oddly enough re Decimal
, I get this interactively
d = decimal.Decimal('23.456')
d
Decimal('23.456')
d - 1
Decimal('22.456')
But when I print it, I get the values
print d
23.456
print d-1
22.456
Use the bultin float function:
>>> d = float('23.456')
>>> d
23.456
>>> d - 1
22.456
See the docs here: http://docs.python.org/library/functions.html#float
My Python seems to do it differently:
>>> s = '23.456'
>>> d = decimal.Decimal(s)
>>> d
Decimal('23.456')
>>> d-1
Decimal('22.456')
What version/OS are you using?
Are you specifically TRYING specifically to use the Decimal arbitrary precision library or are you just struggling to convert a string to a Python float?
If you are TRYING to use Decimal:
>>> import decimal
>>> s1='23.456'
>>> s2='1.0'
>>> decimal.Decimal(s1) - decimal.Decimal(s2)
Decimal('22.456')
>>> s1='23.456'
>>> s2='1'
>>> decimal.Decimal(s1) - decimal.Decimal(s2)
Decimal('22.456')
Or, what I think is more likely, you are trying to just convert a string to a Python floating point value:
>>> s1='23.456'
>>> s2='1'
>>> float(s1)-float(s2)
22.456
>>> float(s1)-1
22.456
>>> float(s1)-1.0
22.456
If using float, when the number gets too large -- x = 29345678.91 for example -- you get results that you might not expect. In this case, float(x)
becomes 2.934567891E7 which seems undesirable especially if working with financial numbers.
In python, to convert a value string to float just do it:
num = "29.0"
print (float(num))
To convert string to decimal
from decimal import Decimal
num = "29.0"
print (Decimal(num))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.