the scootabug virus

How to Serial.print a Double on an Arduino

by on Nov.22, 2008, under Arduino, Code Library

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) ;
}
}
Be Sociable, Share!
:, , , ,

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...