Go Down

Topic: How to Convert Float to String with specific Format (Leading Zero,precision)? (Read 4 times) previous topic - next topic

adrianusp

Hello, i want to convert float to string with a format i needed, ex: float 23.33 to string 023.3 ; 2.56 to string 002.6; -45.66 to string -045.7 then print it via serial and store in SD Card. Could you suggest what function i should use? i will deal with negative number also so straight adding of leading zero depends on string length will cause error in the negative number. Before using arduino, i used to be a basic language(bascom) user, in bascom there is format and fusing. Thanks

ps: i had try using dtostrf which is only specify how many number behind the decimal separator, not how many in front of it
Once you tasted flight, you will walk the earth with eyes turned skywards - Da Vinci

Krodal

Well, you ran into a problem.

Normally the sprintf() function would do this, but the Arduino does not have the floating point enabled for the sprintf() function.
If you try this: https://gist.github.com/2343665 you will see that it prints a '?' for the sprintf() function.
You could enable the floating point for sprintf: http://srejbi.info/posts/16_arduino-printf-scanf-floats
Or you could write your own code, like these:
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1164927646
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1207226548/11#11

I hope someone else knows a better solution ...

cjdelphi


dxw00d


adrianusp


Well, you ran into a problem.

Normally the sprintf() function would do this, but the Arduino does not have the floating point enabled for the sprintf() function.
If you try this: https://gist.github.com/2343665 you will see that it prints a '?' for the sprintf() function.
You could enable the floating point for sprintf: http://srejbi.info/posts/16_arduino-printf-scanf-floats
Or you could write your own code, like these:
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1164927646
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1207226548/11#11

I hope someone else knows a better solution ...


well, finally i decide to multiply my float by 100 then sprintf it as integer, that gives my what i want (i could later divide it again with 100 in the other end of the system) but i ran into another trouble. when dealing with negative number, the negative sign will consumes 1 places, thus reducing my resolution. Any idea how to solved this?

Thanks for the response
Once you tasted flight, you will walk the earth with eyes turned skywards - Da Vinci

PaulS

Separate the integer portion of the number from the fractional portion. Deal with the two parts as separate integers, after multiplying the fractional portion by some factor of 10, and rounding appropriately.

Krodal


Go Up