0

I can't get the hang of rounding in micropython

a=round(86.86, 1)
print (a)
86.90001

surely there must be a way to limit to one dp & get it to round up?

Kris Mclean
  • 21
  • 2
  • 7
  • 2
    Possible duplicate of [Python 3 Float Decimal Points/Precision](https://stackoverflow.com/questions/14540143/python-3-float-decimal-points-precision) – Carcigenicate Feb 18 '19 at 03:15
  • 1
    You'll need to format it as a string. Apparently that number can't be accurately represented using floats – Carcigenicate Feb 18 '19 at 03:16
  • I don't get why micro python (where print (86.9) gives 86.900001) and python (where print 86.9 gives 86.9) are so different in this regard – Kris Mclean Feb 18 '19 at 07:35
  • It might be related to the types of floating point numbers used. Micropython might use floats, where Python uses double precision numbers (just a guess). – Carcigenicate Feb 18 '19 at 13:58
  • Handling of floating point numbers in MicroPython is dependent on the specific implementation. Some versions (WiPy 1.0 for example) don't even support floats! The only definitive reference I can easily find is [this](http://docs.micropython.org/en/latest/genrst/builtin_types.html#float) but from the [forum](https://forum.micropython.org/) it seems clear that most MicroPython implementations use a 32-bit single-precision float. – nekomatic Feb 18 '19 at 15:07
  • So I normally get around precision problems via the round cmd. But when round(86.86, 1) returns 86.900001 there seems to be no mechanism for limiting the number of decimal places? – Kris Mclean Feb 19 '19 at 02:49
  • The mechanism for limiting the number of decimal places is to format the number into a string, e.g. `'{:.1f}'.format(round(86.86, 1))`. It simply isn't possible to store some numbers exactly in a binary floating-point format, just as it isn't possible to store 1/7 exactly in a decimal format. Exactly the same issue exists in desktop Python, you just don't notice it as often because desktop Python uses a higher internal precision. – nekomatic Feb 19 '19 at 15:02
  • See https://docs.python.org/3.6/tutorial/floatingpoint.html#tut-fp-issues for more detail… – nekomatic Feb 19 '19 at 15:16

0 Answers0