1

I am aware of floating point being inaccurate and would like to know the best way to get 0.08354 instead of (0.08353999999999999) when I do the following in Python:

d = 8.354/100

print (d)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
dh-dev
  • 33
  • 1
  • 1
  • 3

2 Answers2

6

If you want absolute precision, use Decimals:

>>> import decimal
>>> decimal.Decimal('8.354') / 10
Decimal('0.8354')
deceze
  • 510,633
  • 85
  • 743
  • 889
  • That's not working here, decimal.Decimal(2110.32)/decimal.Decimal(0.24) = Decimal('8793.000000000001007527394847'). Any other solutions? – Deekshant Aug 18 '23 at 19:42
  • You’re already using floats there. Don’t. Use string literals instead, as shown in my answer. – deceze Aug 19 '23 at 01:32
  • That worked, decimal.Decimal(str(2110.32))/decimal.Decimal(str(0.24))=Decimal('8793'). Now I am wondering about the tradeoff between 3 conversions (float->str, float->str, str->int) and the accuracy required in my use case. They've gotta add some better methods for this on Python. – Deekshant Aug 20 '23 at 03:25
  • Why `decimal.Decimal(str(2110.32))`!? Just do `decimal.Decimal('2110.32')`! – deceze Aug 20 '23 at 07:02
  • Because 2110.32 isn't a constant. It is an input which can be any arbitrary number. – Deekshant Aug 21 '23 at 14:04
  • Then your case isn’t what you present here. You best write a new question with all the details. – deceze Aug 21 '23 at 21:24
4

Use the builtin round() function:

>>> d = 8.354/100
>>> d
0.08353999999999999
>>> round(d, 6)
0.08354
>>> 
Christian Dean
  • 22,138
  • 7
  • 54
  • 87