Page 1 of 1

Convert str to float

Posted: Tue May 11, 2021 3:24 pm
by ebolisa
Hi all,
The following code returns 4030.332 instead of 4030.33158 on an ESP32 and Rpi Pico. What happens to the rest of the digits?
Using Python on Linux/Windoze, the code returns correctly all digits.
TIA

Code: Select all

lat = '4030.33158'
lat = float(lat)
# lat = lat / 100
# lat = str(lat)
print(type(lat))
print(lat)
>>> 4030.332

Re: Convert str to float

Posted: Tue May 11, 2021 3:49 pm
by dhylands
Micropython uses 32-bit floats by default, so you only get six significant digits.

You can get more digits printed by specifying the number of digits explicitly:

Code: Select all

>>> print('{:.12f}'.format(lat))
4030.331611633301
Just don't expect anything beyond 6 significant digits with 32-bit floats. I believe it's possible to compile the firmware with 64-bit floats.

Re: Convert str to float

Posted: Tue May 11, 2021 3:57 pm
by ebolisa
Thank you!

Re: Convert str to float

Posted: Wed May 12, 2021 10:29 pm
by rcolistete
Here are some ESP32 firmwares with DP (double precision), ulab, etc :
https://gitlab.com/rcolistete/micropyth ... ster/ESP32

Yeah, I need to update with newer versions of firmware and ulab.

Re: Convert str to float

Posted: Mon May 31, 2021 11:19 pm
by seaside_motors
dhylands wrote:
Tue May 11, 2021 3:49 pm
Micropython uses 32-bit floats by default, so you only get six significant digits.

You can get more digits printed by specifying the number of digits explicitly:

Code: Select all

>>> print('{:.12f}'.format(lat))
4030.331611633301
Just don't expect anything beyond 6 significant digits with 32-bit floats. I believe it's possible to compile the firmware with 64-bit floats.
Thank You! I have been trying to get the output of a temp sensor to explicitly output only 2 decimal places. This tiny snipped of code was all that I needed! Thanks to both the topic starter and Dave for the silver bullet for my werewolf!

Code: Select all

#    oled.text("Temp: "+str(tempF),6,12) ##old
      oled.text("Temp: {:.2f}".format(tempF),6,12)  ##new