1

Result of a simple division -34.11/2 returns -17.055 Is there a python function that would return round up decimal? I am expecting to see -17.06

And yes I checked these answers, but neither can answer this question: Round up to Second Decimal Place in Python

How to round to nearest decimal in Python

Increment a Python floating point value by the smallest possible amount Python round to nearest 0.25

Any help would be greatly appreciated. Thanks!

hod
  • 750
  • 7
  • 21
  • 3
    `import numpy as np` `np.round(0.05, 2)` – Andrew Mar 26 '20 at 13:27
  • This is, actually, answered by the questions you linked to. Please read the documentation on [Floating Point Arithmetic: Issues and Limitations](https://docs.python.org/3/tutorial/floatingpoint.html#tut-fp-issues). – Arya McCarthy Mar 26 '20 at 13:29

1 Answers1

4

This is a floating point limitation; get around it by using decimal.Decimal.

>>> from decimal import Decimal
>>> Decimal(-34.11/2)  # See? Not quite the value you thought.
Decimal('-17.05499999999999971578290569595992565155029296875')
>>> Decimal(-34.11) / Decimal(2)  # This doesn't quite work either, because -34.11 is already a little bit off.
Decimal('-17.05499999999999971578290570')
>>> Decimal("-34.11") / Decimal("2")
Decimal('-17.055')
>>> round(Decimal("-34.11") / Decimal("2"), 2)
Decimal('-17.06')
Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56