aboutsummaryrefslogtreecommitdiff
path: root/cores/arduino/Print.cpp
diff options
context:
space:
mode:
authorDavid A. Mellis <d.mellis@arduino.cc>2009-01-25 15:44:17 +0000
committerDavid A. Mellis <d.mellis@arduino.cc>2009-01-25 15:44:17 +0000
commitd7500ba2289f33c844782a9e10fb6c6cb3a212e4 (patch)
treeb4b1a56fe520f4eefce201c51bc89655eb0e1087 /cores/arduino/Print.cpp
parentc0550aac8c93e81828a8cc10ac2e4ee5e0f83e16 (diff)
fixing / improving printFloat() from Mikal Hart
Diffstat (limited to 'cores/arduino/Print.cpp')
-rwxr-xr-xcores/arduino/Print.cpp49
1 files changed, 33 insertions, 16 deletions
diff --git a/cores/arduino/Print.cpp b/cores/arduino/Print.cpp
index 143f15d..d4833da 100755
--- a/cores/arduino/Print.cpp
+++ b/cores/arduino/Print.cpp
@@ -81,7 +81,7 @@ void Print::print(long n, int base)
void Print::print(double n)
{
- printFloat(n*100, 2);
+ printFloat(n, 2);
}
void Print::println(void)
@@ -167,20 +167,37 @@ void Print::printNumber(unsigned long n, uint8_t base)
'A' + buf[i - 1] - 10));
}
-void Print::printFloat(double number, uint8_t scale)
+void Print::printFloat(double number, uint8_t digits)
{
- double mult = pow(10,scale);
- double rounded = floor(number /mult);
- double biground = rounded * mult;
- double remainder = (number - biground);
- remainder = remainder / mult;
- print(long(rounded));
- print(".");
-
- while (scale--) {
- double toPrint = floor(remainder * 10);
- print(int(toPrint));
- remainder -= (toPrint/10);
- remainder *= 10;
+ // Handle negative numbers
+ if (number < 0.0)
+ {
+ print('-');
+ number = -number;
+ }
+
+ // Round correctly so that print(1.999, 2) prints as "2.00"
+ double rounding = 0.5;
+ for (uint8_t i=0; i<digits; ++i)
+ rounding /= 10.0;
+
+ number += rounding;
+
+ // Extract the integer part of the number and print it
+ unsigned long int_part = (unsigned long)number;
+ double remainder = number - (double)int_part;
+ print(int_part);
+
+ // Print the decimal point, but only if there are digits beyond
+ if (digits > 0)
+ print(".");
+
+ // Extract digits from the remainder one at a time
+ while (digits-- > 0)
+ {
+ remainder *= 10.0;
+ int toPrint = int(remainder);
+ print(toPrint);
+ remainder -= toPrint;
}
-} \ No newline at end of file
+}