PROBLEM


When I use floating point numbers, I get a strange rounding problem.

Why do I get lots of digits displayed in a number?

Strange rounding problem in Python/MicroPython.

Lots of digits displayed after a number.

18.9 gets displayed as 18.89999


CAUSE


https://github.com/bbcmicrobit/micropython/issues/367#issuecomment-258059673


The microbit uses 30-bit floating point and 18.9 is parsed correctly/accurately but it's then rounded down to 18.899999 when stored in 30 bits.


Floating point numbers are always going to have inaccuracies and you should use formatting like "%.2f" if you want a certain number of digits in the output.


WORKAROUND

 

number = 18.9
display.scroll("%.1f" % number)

 

DISCUSSION


display.scroll("%.1f" % number)


This uses Python string formatters:

https://pyformat.info/


If you have ever coded in C, they are similar to the format specifiers for the printf() function in C.


% inside the quotes means to specify the format of the next parameter

f specifies to interpret the next parameter as a floating point number.

. implies that you are specifying field-width and precision

Because there is no number before the . the field-width is not specified and defaults are used

1 after the dot means the precision is set to 1DP.


The string formatting operator % will apply the parameter(s) to the string at the start, using the % format specifiers in that quoted string.


e.g. to display a single string, you could use


print("My name is %s how cool is that!" % name)


The % operator at the end requires only 1 parameter, so if you have multiple parameters to 'fill into the string format', you have to use brackets like this:


print("My first name is %s my surname is %s I am %d years old" % (firstname, surname, age))


LAST REVIEWED


10 NOV 2016