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
  • 168,988
  • 22
  • 228
  • 312
dh-dev
  • 33
  • 1
  • 3

2 Answers2

6

If you want absolute precision, use Decimals:

>>> import decimal
>>> decimal.Decimal('8.354') / 10
Decimal('0.8354')
deceze
  • 491,798
  • 79
  • 706
  • 853
3

Use the builtin round() function:

>>> d = 8.354/100
>>> d
0.08353999999999999
>>> round(d, 6)
0.08354
>>> 
Christian Dean
  • 20,986
  • 7
  • 47
  • 78