Skip to content

Commit 369b7bb

Browse files
committed
fix(printf): remove float comparison
Add more float test cases
1 parent e9375ed commit 369b7bb

2 files changed

Lines changed: 13 additions & 5 deletions

File tree

printf.c

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -363,11 +363,7 @@ static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, d
363363

364364
if (prec == 0U) {
365365
diff = value - (double)whole;
366-
if (diff > 0.5) {
367-
// greater than 0.5, round up, e.g. 1.6 -> 2
368-
++whole;
369-
}
370-
else if ((diff == 0.5) && (whole & 1)) {
366+
if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) {
371367
// exactly 0.5 and ODD, then round up
372368
// 1.5 -> 2, but 2.5 -> 2
373369
++whole;

test/test_suite.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1036,6 +1036,15 @@ TEST_CASE("float", "[]" ) {
10361036
test::sprintf(buffer, "%.0f", 34.1415354);
10371037
REQUIRE(!strcmp(buffer, "34"));
10381038

1039+
test::sprintf(buffer, "%.0f", 1.3);
1040+
REQUIRE(!strcmp(buffer, "1"));
1041+
1042+
test::sprintf(buffer, "%.0f", 1.55);
1043+
REQUIRE(!strcmp(buffer, "2"));
1044+
1045+
test::sprintf(buffer, "%.1f", 1.64);
1046+
REQUIRE(!strcmp(buffer, "1.6"));
1047+
10391048
test::sprintf(buffer, "%.2f", 42.8952);
10401049
REQUIRE(!strcmp(buffer, "42.90"));
10411050

@@ -1082,6 +1091,9 @@ TEST_CASE("float", "[]" ) {
10821091
test::sprintf(buffer, "%.0f", 3.5);
10831092
REQUIRE(!strcmp(buffer, "4"));
10841093

1094+
test::sprintf(buffer, "%.0f", 4.5);
1095+
REQUIRE(!strcmp(buffer, "4"));
1096+
10851097
test::sprintf(buffer, "%.0f", 3.49);
10861098
REQUIRE(!strcmp(buffer, "3"));
10871099

0 commit comments

Comments
 (0)