Because Arduino language is rather low-level (C-based), such a function is not so straightforward or available as one might think.
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);}}
Thanks for writing this :)
ReplyDeleteyou had a copy paste error
"String string = String((int)(input*pow(10,decimalPlaces)));"
Thanks a lot, I corrected it.
ReplyDeleteWorks great! Thanks!
ReplyDeleteYou are welcome!
ReplyDeletewhy i am getting -2.4889 in this example :
ReplyDeletedouble 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