Convert str to float

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
ebolisa
Posts: 55
Joined: Thu Feb 21, 2019 11:43 am
Location: Madrid, Spain

Convert str to float

Post by ebolisa » Tue May 11, 2021 3:24 pm

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

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Convert str to float

Post by dhylands » 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.

User avatar
ebolisa
Posts: 55
Joined: Thu Feb 21, 2019 11:43 am
Location: Madrid, Spain

Re: Convert str to float

Post by ebolisa » Tue May 11, 2021 3:57 pm

Thank you!

User avatar
rcolistete
Posts: 352
Joined: Thu Dec 31, 2015 3:12 pm
Location: Brazil
Contact:

Re: Convert str to float

Post by rcolistete » Wed May 12, 2021 10:29 pm

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.
My "MicroPython Samples". My "MicroPython Firmwares" with many options (double precision, ulab, etc).

seaside_motors
Posts: 17
Joined: Thu Mar 25, 2021 4:19 am

Re: Convert str to float

Post by seaside_motors » Mon May 31, 2021 11:19 pm

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

Post Reply