Monday, January 9, 2012

Simple Arduino double-to-string function

Because Arduino language is rather low-level (C-based), such a function is not so straightforward or available as one might think.

I could not find this in the libraries or a simple solution online, so I made one on my own, and I think it is quite general and handy.

Just input the double and the number of decimal places desired. The function:

//Rounds down (via intermediary integer conversion truncation)
String doubleToString(double input,int decimalPlaces){
if(decimalPlaces!=0){
String string = String((int)(input*pow(10,decimalPlaces)));
if(abs(input)<1){
if(input>0)
string = "0"+string;
else if(input<0)
string = string.substring(0,1)+"0"+string.substring(1);
}
return string.substring(0,string.length()-decimalPlaces)+"."+string.substring(string.length()-decimalPlaces);
}
else {
return String((int)input);
}
}

5 comments:

  1. Thanks for writing this :)
    you had a copy paste error
    "String string = String((int)(input*pow(10,decimalPlaces)));"

    ReplyDelete
  2. Thanks a lot, I corrected it.

    ReplyDelete
  3. why i am getting -2.4889 in this example :
    double f = 4.064728;
    String sf =doubleToString(f,4); // <--- number of decimals
    Serial.println(sf);// i am getting -2.4889
    PS if decimal =3 instead of 4 it work fine

    ReplyDelete