diff --git a/CHANGELOG.md b/CHANGELOG.md index 81451374..38e266e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Show output from successful compile - `--min-free-space=N` command-line argument to fail if free space is below requred value - Add `_BV()` macro. +- Support for `dtostrf()` ### Changed - Fix copy/paste error to allow additional warnings for a platform diff --git a/SampleProjects/TestSomething/test/stdlib.cpp b/SampleProjects/TestSomething/test/stdlib.cpp index ce0b72fb..31bd0735 100644 --- a/SampleProjects/TestSomething/test/stdlib.cpp +++ b/SampleProjects/TestSomething/test/stdlib.cpp @@ -43,4 +43,12 @@ unittest(library_tests_itoa) } +unittest(library_tests_dtostrf) +{ + float num = 123.456; + char buffer[10]; + dtostrf(num, 7, 3, buffer); + assertEqual(strncmp(buffer, "123.456", sizeof(buffer)), 0); +} + unittest_main() diff --git a/cpp/arduino/stdlib.cpp b/cpp/arduino/stdlib.cpp index 931e5138..bb920200 100644 --- a/cpp/arduino/stdlib.cpp +++ b/cpp/arduino/stdlib.cpp @@ -18,6 +18,7 @@ ** is out of range. */ +#include #include #include @@ -59,3 +60,22 @@ char *itoa(int N, char *str, int base) return str; } #endif + + /* + The dtostrf() function converts the double value passed in val into + an ASCII representationthat will be stored under s. The caller is + responsible for providing sufficient storage in s. + + Conversion is done in the format “[-]d.ddd”. The minimum field width + of the output string (including the ‘.’ and the possible sign for + negative values) is given in width, and prec determines the number of + digits after the decimal sign. width is signed value, negative for + left adjustment. + + The dtostrf() function returns the pointer to the converted string s. + */ + + char *dtostrf(double __val, signed char __width, unsigned char __prec, char *__s) { + sprintf(__s, "%*.*f", __width, __prec, __val); + return __s; + } diff --git a/cpp/arduino/stdlib.h b/cpp/arduino/stdlib.h index c685e645..6b8ee865 100644 --- a/cpp/arduino/stdlib.h +++ b/cpp/arduino/stdlib.h @@ -12,3 +12,6 @@ * https://stackoverflow.com/questions/190229/where-is-the-itoa-function-in-linux */ char *itoa(int val, char *s, int radix); + + // another function provided by Arduino + char * dtostrf(double __val, signed char __width, unsigned char __prec, char *__s);