mirror of
https://github.com/arduino/Arduino.git
synced 2024-11-30 11:24:12 +01:00
fixing / improving printFloat() from Mikal Hart
This commit is contained in:
parent
473cf103b8
commit
854c69dfde
@ -81,7 +81,7 @@ void Print::print(long n, int base)
|
|||||||
|
|
||||||
void Print::print(double n)
|
void Print::print(double n)
|
||||||
{
|
{
|
||||||
printFloat(n*100, 2);
|
printFloat(n, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Print::println(void)
|
void Print::println(void)
|
||||||
@ -167,20 +167,37 @@ void Print::printNumber(unsigned long n, uint8_t base)
|
|||||||
'A' + buf[i - 1] - 10));
|
'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);
|
// Handle negative numbers
|
||||||
double rounded = floor(number /mult);
|
if (number < 0.0)
|
||||||
double biground = rounded * mult;
|
{
|
||||||
double remainder = (number - biground);
|
print('-');
|
||||||
remainder = remainder / mult;
|
number = -number;
|
||||||
print(long(rounded));
|
}
|
||||||
print(".");
|
|
||||||
|
|
||||||
while (scale--) {
|
// Round correctly so that print(1.999, 2) prints as "2.00"
|
||||||
double toPrint = floor(remainder * 10);
|
double rounding = 0.5;
|
||||||
print(int(toPrint));
|
for (uint8_t i=0; i<digits; ++i)
|
||||||
remainder -= (toPrint/10);
|
rounding /= 10.0;
|
||||||
remainder *= 10;
|
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user