2

I am trying to understand this. if I want to multiply a long and decimal number... I get the wrong result.

Example:

>>>import decimal

>>>division = decimal.Decimal(818191513483616911) / decimal.Decimal(2)
>>>print(division)
409095756741808455.5    # good
>>>multiply = decimal.Decimal(409095756741808455.5) * decimal.Decimal(2)
>>>print(multiply)
818191513483616896    # wrong. how to get 818191513483616911?
CncMess
  • 23
  • 5
  • 2
    hint: `409095756741808455.5` isn't 409095756741808455.5. Converting an a float (which has already lost precision) to a Decimal is to late. – Mikael Öhman Aug 13 '22 at 11:00
  • Try: `decimal.Decimal("409095756741808455.5") * decimal.Decimal(2)` – Jiří Baum Aug 13 '22 at 11:02
  • @Jiří Baum Yes, string is a solution. I can use it, but is there some better pythonic way for this? – CncMess Aug 13 '22 at 11:06
  • No, string is unfortunately the only way; in Python, bare numbers with a decimal point are interpreted as `float`, with the results that you observe... A lot of the time, of course, you'll be reading the numbers from a file (or some other outside source), so you'll be starting with a string anyway, but if you need to specify a non-integer `Decimal` directly in Python, you have to quote it. – Jiří Baum Aug 13 '22 at 11:08
  • 1
    This is a much-asked question - see for example https://stackoverflow.com/q/62927128/270986, which is just one of many questions along these lines. I was unable to find anything that's a really good duplicate, though. – Mark Dickinson Aug 13 '22 at 11:57

0 Answers0