How to Serial.print a Double on an Arduino
November 22, 2008
I found the following code on the Arduino forums and decided to post it here for future reference.
It allows you to print a double/float to the serial port. You’ll need to edit the last line if you didn’t want a carriage return after the value is printed. It works a treat.
void printDouble(double val, byte precision){
// prints val with number of decimal places determine by precision
// precision is a number from 0 to 6 indicating the desired decimial places
// example: printDouble( 3.1415, 2); // prints 3.14 (two decimal places)
Serial.print (int(val)); //prints the int part
if( precision > 0) {
Serial.print("."); // print the decimal point
unsigned long frac;
unsigned long mult = 1;
byte padding = precision -1;
while(precision--)
mult *=10;
if(val >= 0)
frac = (val - int(val)) * mult;
else
frac = (int(val)- val ) * mult;
unsigned long frac1 = frac;
while( frac1 /= 10 )
padding--;
while(padding--)
Serial.print("0");
Serial.println(frac,DEC) ;
}
}
Leave a Reply