Skip to content

use sprintf-based implementation for dtostrf #122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 6 additions & 58 deletions cores/arduino/stdlib_noniso.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -147,61 +147,9 @@ char* ultoa( unsigned long val, char *string, int radix )
return string;
}

char * dtostrf(double number, signed char width, unsigned char prec, char *s) {

if (isnan(number)) {
strcpy(s, "nan");
return s;
}
if (isinf(number)) {
strcpy(s, "inf");
return s;
}

if (number > 4294967040.0 || number < -4294967040.0) {
strcpy(s, "ovf");
return s;
}

char* out = s;
int signInt_Part = 1;

// Handle negative numbers
if (number < 0.0) {
signInt_Part = -1;
number = -number;
}

// calc left over digits
if (prec > 0)
{
width -= (prec + 1);
}

// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for (uint8_t i = 0; i < prec; ++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;
out += sprintf(out, "%*ld", width, int_part * signInt_Part);

// Print the decimal point, but only if there are digits beyond
if (prec > 0) {
*out = '.';
++out;
// Copy character by character to 'out' string
for (unsigned char decShift = prec; decShift > 0; decShift--) {
remainder *= 10.0;
sprintf(out, "%d", (int)remainder);
out++;
remainder -= (double)(int)remainder;
}
}

return s;
}
char *dtostrf (double val, signed char width, unsigned char prec, char *sout) {
char fmt[20];
sprintf(fmt, "%%%d.%df", width, prec);
sprintf(sout, fmt, val);
return sout;
}