Pages: [1]   Go Down
Author Topic: Simple way to convert from Floating point to String  (Read 538 times)
0 Members and 1 Guest are viewing this topic.
Brasil
Offline Offline
Full Member
***
Karma: 4
Posts: 125
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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;
}
Logged


Pages: [1]   Go Up
Jump to: