Go Down

Topic: Simple way to convert from Floating point to String (Read 652 times) previous topic - next topic

ivanseidel

Well, I searched for some time on the Internet for an reliable way to convert from a floating point to String, but I found none in 10 secconds and did my self that.

If you need, this is the code (Also explained a bit):

Code: [Select]
String floatToString(float f, int decimals = 2){
/*
Transforms the floating point string process:
eg.: using decimals = 2, input: 1.23456
1.23456 * (pow(10, 2+1)
1.23456 * 1000 = 1234 (as a long)
now, let's move digits asside:
3 goes to 4, 2 goes to 3.
Stages: "1234"
"1233"
"1223"
Not, put a dot in the place of the separator
"1.23"

*/
long fLong = f*(pow(10,decimals+1));
String longString = String(fLong);
int len = longString.length();

for(int i = 0; i < decimals; i++){
longString[len - 1 - i] = longString[len - 2 - i];
}
longString[len - decimals - 1] = '.';

return longString;
}
Arduino DueTimer | https://github.com/ivanseidel/DueTimer
Arduino Thread | https://github.com/ivanseidel/ArduinoThread

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy