Go Down

Topic: Print Rounded Float or Double to screen or Serial (Read 546 times) previous topic - next topic

meaghan

I modified code originally posted by mem here (http://forum.arduino.cc/index.php?topic=44216.msg320124#msg320124) to round a double before printing it to an LCD.  You could easily modify this code to print to the Serial monitor, too.

Code: [Select]
/*Prints decimal to LCD
*Takes value, precision as arguments
*Rounds decimal
*/
void printDouble(double val, byte precision) {
  lcd.print (int(val));
  if( precision > 0) {
    lcd.print(".");
    unsigned long frac, mult = 1;
    byte padding = precision -1;
    while(precision--){
      mult *=10;
    }
    if(val >= 0){
      frac = (val - int(val)) * mult;
      //Rounding
      if(((val-int(val))*mult*10)-frac*10>=5){
        frac++;
      }
    }
    else{
      frac = (int(val) - val) * mult;
      //Rounding
      if(((int(val)-val)*mult*10)-frac*10>=5){
        frac++;
      }
    }   
    unsigned long frac1 = frac;
    while(frac1 /= 10){
      padding--;
    }
    while(padding--){
      lcd.print("0");
    }
    lcd.print(frac,DEC) ;
  }
}

Go Up