printing a double variable

Serial.print does not print floating point. Here is a sketch with a function you can use to display the number of decimal places you want.

double x; 
double y; 
double z; 
 
void printDouble( double val, unsigned int precision){
// prints val with number of decimal places determine by precision
// NOTE: precision is 1 followed by the number of zeros for the desired number of decimial places
// example: printDouble( 3.1415, 100); // prints 3.14 (two decimal places)

    Serial.print (int(val));  //prints the int part
    Serial.print("."); // print the decimal point
    unsigned int frac;
    if(val >= 0)
        frac = (val - int(val)) * precision;
    else
        frac = (int(val)- val ) * precision;
    Serial.println(frac,DEC) ;
} 
 
void  setup(){
  Serial.begin(9600);
  Serial.println("Print floating point example");   
  printDouble( 3.1415, 100);  // example of call to printDouble to print pi to two decimal places
  x = 10; 
  y = 3.1; 
  z = x / y;   
}
 
 
 void loop(){
   printDouble(z,10);   // one decimal place
   printDouble(z,100);  // two decimal places
   printDouble(z,1000); // three decimal places
   z = z + .1;
   delay(100);
 }
1 Like