Advertisement
Guest User

Untitled

a guest
Apr 24th, 2010
1,564
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. void printFloat(double number, int digits)
  2. {
  3.   // Handle negative numbers
  4.   if (number < 0.0)
  5.   {
  6.      Serial.print('-');
  7.      number = -number;
  8.   }
  9.  
  10.   // Round correctly so that print(1.999, 2) prints as "2.00"
  11.   double rounding = 0.5;
  12.   for (uint8_t i=0; i<digits; ++i)
  13.     rounding /= 10.0;
  14.  
  15.   number += rounding;
  16.  
  17.   // Extract the integer part of the number and print it
  18.   unsigned long int_part = (unsigned long)number;
  19.   double remainder = number - (double)int_part;
  20.   Serial.print(int_part);
  21.  
  22.   // Print the decimal point, but only if there are digits beyond
  23.   if (digits > 0)
  24.     Serial.print(".");
  25.  
  26.   // Extract digits from the remainder one at a time
  27.   while (digits-- > 0)
  28.   {
  29.     remainder *= 10.0;
  30.     int toPrint = int(remainder);
  31.     Serial.print(toPrint);
  32.     remainder -= toPrint;
  33.   }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement