Advertisement
Guest User

Untitled

a guest
Apr 24th, 2010
690
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. char* floatToChar(double number, int digits)
  2. {
  3.   char* finishedChar;
  4.   char* intPartStr;
  5.   char* decimalValueStr;
  6.  
  7.   // Handle negative numbers
  8.   if (number < 0.0)
  9.   {
  10.     //put a - on the string
  11.      finishedChar="-";
  12.      Serial.print("\n FinishedChar after minus: "); Serial.print(finishedChar);
  13.      number = -number;
  14.   }
  15.  
  16.   // Round correctly so that print(1.999, 2) prints as "2.00"
  17.   double rounding = 0.5;
  18.   for (uint8_t i=0; i<digits; ++i)
  19.   {
  20.     rounding /= 10.0;
  21.   }
  22.  
  23.   number += rounding;
  24.  
  25.   // Extract the integer part of the number and print it
  26.   unsigned long int_part = (unsigned long)number;
  27.   double remainder = number - (double)int_part;
  28.   //at the integer part to the string
  29.   itoa(int_part, intPartStr, 10);
  30.   strcat(finishedChar, intPartStr);
  31.   Serial.print("\n finishedChar after intPart: "); Serial.print(finishedChar);
  32.  
  33.   // Add a decimal point, but only if there are digits beyond
  34.   if (digits > 0)
  35.   {
  36.     strcat(finishedChar, ".");
  37.     Serial.print("\n finishedChar after decimal: "); Serial.print(finishedChar);
  38.   }
  39.  
  40.   // Extract digits from the remainder one at a time
  41.   while (digits-- > 0)
  42.   {
  43.     remainder *= 10.0;
  44.     int toPrint = int(remainder);
  45.     itoa(toPrint, decimalValueStr, 10);
  46.     strcat(finishedChar, decimalValueStr);
  47.     Serial.print("\n finishedChar remainder: "); Serial.print(finishedChar); Serial.print(" decimal value: "); Serial.print(decimalValueStr);
  48.     remainder -= toPrint;
  49.   }
  50.  
  51.   return finishedChar;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement