1

I am working with Python and have two strings which contain float style values, For example:

a = '0.0000001'
b = '0.0003599'

I am looking for a solution to simply add or subtract the two values together to a new string, keeping the decimal precision intact. I have tried converting them to a float and using a + b etc but this seems to be inconsistent.

So the resulting string in this example would be string

c = '0.0003600'

I've been over a number of examples/methods and not quite found the answer. Any help appreciated.

4
  • 7
    have you looked at the decimal module? Commented Jan 15, 2018 at 21:58
  • "but this seems to be inconsistent." can you elaborate on that? What are you seeing exactly, and what is the problem? What would the solution give you? Commented Jan 15, 2018 at 22:00
  • Are you saying you want the result to be '0.0003600' rather than '0.00036'? And you don't know ahead of time how many decimals will be required? Commented Jan 15, 2018 at 22:00
  • thats correct. To be more precise i am looking, in this example, to add A to B, so 0.0003600 + 0.0000001. So the decimal precision would keep the legnth of B. when using floats the precision gets lost Commented Jan 15, 2018 at 22:05

3 Answers 3

2

Looks like the decimal module should do what you want:

>>> from decimal import *
>>> a = '0.0000001'
>>> b = '0.0003599'
>>> Decimal(a)+Decimal(b)
Decimal('0.0003600')
Sign up to request clarification or add additional context in comments.

1 Comment

* imports are discouraged. from decimal import Decimal should be sufficient. docs.python.org/2/howto/doanddont.html
1

mpmath library could do arbitrary precision float arithmetic:

>>> from mpmath import mpf
>>> a = mpf('0.0003599')
>>> b = mpf('0.0000001')
>>> print(a + b)
0.00036

Comments

0

Converting to a float is fine for all cases I can think of:

>>> str(sum(float(i) for i in (a, b)))
'0.00036'
>>> str(sum(map(float, (a, b))))
'0.00036'
>>> str(float(a) + float(b))
'0.00036'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.