user1091458
user1091458

Reputation:

How do I get Decimal to reflect value correctly?

I need to perform many math operations on numbers that look like 104.950178 - i.e. having multiple decimal places. It ranges from 4 decimal places to 8 decimal places with an occasional 10 decimal place number.

After much reading on Stack Overflow, I understand that I should not use float but instead use Decimal, because float is base 2 and Decimal is base 10. Having many math operations, float will give a result with error, which was not what I wanted, so I went with Decimal.

Everything was working fine until I encountered:

from decimal import *
Decimal(0.1601).quantize(Decimal('.0001'), rounding=ROUND_FLOOR) #returned Decimal('0.1600')

I need the numbers to be reflected exactly as they are. Can you please advise if there is another number system to use in Python 3, or if there is a way to get Decimal to take the number given as it is without changing its value?

Note: I added the "quantize..." portion of the code due to the comment by Mark to make it a MVCE. I took for granted the output and forgot that every Decimal in this part of my code was processed to truncate at 4 decimal points.

Nevertheless, @jonrsharpe is really sharp. He saw my question and immediately knew (before the "quantize..." edit) where the problem was. Thanks!

Upvotes: 0

Views: 99

Answers (1)

user1091458
user1091458

Reputation:

Instead of:

a = 0.1601
Decimal(a)

I used:

a = '0.1601'
Decimal(a)

Defined it as a string instead, and Decimal reflected the value exactly. I hope this helps someone.

Upvotes: 1

Related Questions