Skip to content

Commit 3bf1d22

Browse files
authored
Merge pull request #269 from boostorg/267
Fix all 9s rounding on the right side of the decimal point with fixed precision
2 parents 38854b2 + ba6a62d commit 3bf1d22

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

include/boost/charconv/detail/dragonbox/floff.hpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4018,9 +4018,10 @@ BOOST_CHARCONV_SAFEBUFFERS to_chars_result floff(const double x, int precision,
40184018
++decimal_dot_pos;
40194019
}
40204020
}
4021-
else if (decimal_exponent_normalized == 0)
4021+
else if (decimal_exponent_normalized == 0 || remaining_digits == 1)
40224022
{
40234023
// For the case 0.99...9 -> 1.00...0, the rounded digit is one before the first digit written.
4024+
// This same case applies for 0.099 -> 0.10 in the precision = 2 instance
40244025
// Note: decimal_exponent_normalized was negative before the increment (++decimal_exponent_normalized),
40254026
// so we already have printed "00" onto the buffer.
40264027
// Hence, --digit_starting_pos doesn't go more than the starting position of the buffer.

test/Jamfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,4 @@ run github_issue_166.cpp ;
7070
run github_issue_166_float128.cpp ;
7171
run github_issue_186.cpp ;
7272
run github_issue_212.cpp ;
73+
run github_issue_267.cpp ;

test/github_issue_267.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Copyright 2025 Matt Borland
2+
// Distributed under the Boost Software License, Version 1.0.
3+
// https://www.boost.org/LICENSE_1_0.txt
4+
//
5+
// See: https://github.com/boostorg/charconv/issues/267
6+
7+
#include <boost/charconv.hpp>
8+
#include <boost/core/lightweight_test.hpp>
9+
10+
template <typename T>
11+
void test(T value, int precision, const char* correct_result)
12+
{
13+
char buffer[64] {};
14+
const auto r = boost::charconv::to_chars(buffer, buffer + sizeof(buffer), value, boost::charconv::chars_format::fixed, precision);
15+
BOOST_TEST_CSTR_EQ(buffer, correct_result);
16+
BOOST_TEST(r);
17+
}
18+
19+
int main()
20+
{
21+
test(0.09, 2, "0.09");
22+
test(0.099, 2, "0.10");
23+
test(0.0999, 2, "0.10");
24+
test(0.09999, 2, "0.10");
25+
test(0.099999, 2, "0.10");
26+
test(0.0999999, 2, "0.10");
27+
test(0.09999999, 2, "0.10");
28+
test(0.099999999, 2, "0.10");
29+
test(0.0999999999, 2, "0.10");
30+
test(0.09999999999, 2, "0.10");
31+
test(0.099999999999, 2, "0.10");
32+
test(0.0999999999999, 2, "0.10");
33+
34+
return boost::report_errors();
35+
}

0 commit comments

Comments
 (0)