Skip to content

Commit 80b42fe

Browse files
committed
fix(printf): fixed support of NaN
(hot) fixes #37
1 parent bf72dfb commit 80b42fe

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ Therefore I decided to write an own, final implementation which meets the follow
2828
- Support of decimal/floating number representation (with an own fast itoa/ftoa)
2929
- Reentrant and thread-safe, malloc free, no static vars/buffers
3030
- LINT and compiler L4 warning free, mature, coverity clean, automotive ready
31-
- Extensive test suite (> 350 test cases) passing
31+
- Extensive test suite (> 370 test cases) passing
3232
- Simply the best *printf* around the net
3333
- MIT license
3434

printf.c

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,14 @@ static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, d
311311
// powers of 10
312312
static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
313313

314+
// test for NaN
315+
if (value != value) {
316+
out('n', buffer, idx++, maxlen);
317+
out('a', buffer, idx++, maxlen);
318+
out('n', buffer, idx++, maxlen);
319+
return idx;
320+
}
321+
314322
// test for negative
315323
bool negative = false;
316324
if (value < 0) {
@@ -341,8 +349,10 @@ static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, d
341349
++whole;
342350
}
343351
}
344-
else if ((diff == 0.5) && ((frac == 0U) || (frac & 1U))) {
345-
// if halfway, round up if odd, OR if last digit is 0
352+
else if (diff < 0.5) {
353+
}
354+
else if ((frac == 0U) || (frac & 1U)) {
355+
// if halfway, round up if odd OR if last digit is 0
346356
++frac;
347357
}
348358

test/test_suite.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#include "catch.hpp"
3232

3333
#include <string.h>
34+
#include <math.h>
3435

3536
namespace test {
3637
// use functions in own test namespace to avoid stdio conflicts
@@ -1019,6 +1020,9 @@ TEST_CASE("length", "[]" ) {
10191020
TEST_CASE("float", "[]" ) {
10201021
char buffer[100];
10211022

1023+
test::sprintf(buffer, "%.4f", NAN); // using the NAN macro of math.h
1024+
REQUIRE(!strcmp(buffer, "nan"));
1025+
10221026
test::sprintf(buffer, "%.4f", 3.1415354);
10231027
REQUIRE(!strcmp(buffer, "3.1415"));
10241028

0 commit comments

Comments
 (0)