Skip to content
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

Add support for '%' type to output floating point values as a percentage. #1060

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
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
12 changes: 9 additions & 3 deletions include/fmt/format-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -539,8 +539,7 @@ struct fixed_stop {
void on_exp(int exp) {
if (!fixed) return;
exp += exp10;
if (exp >= 0)
precision += exp;
if (exp >= 0) precision += exp;
}

bool operator()(char*, int& size, uint64_t remainder, uint64_t divisor,
Expand Down Expand Up @@ -656,7 +655,14 @@ void sprintf_format(Double value, internal::buffer& buf,
*format_ptr++ = '*';
}
if (std::is_same<Double, long double>::value) *format_ptr++ = 'L';
char type = spec.type ? spec.type : 'g';

char type = spec.type;

if (type == '%') {
type = 'f';
} else if (type == 0) {
type = 'g';
}
#if FMT_MSC_VER
if (type == 'F') {
// MSVC's printf doesn't support 'F'.
Expand Down
30 changes: 26 additions & 4 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -1274,6 +1274,9 @@ FMT_CONSTEXPR void handle_float_type_spec(char spec, Handler&& handler) {
case 'F':
handler.on_fixed();
break;
case '%':
handler.on_percent();
break;
case 'a':
case 'A':
handler.on_hex();
Expand Down Expand Up @@ -1338,6 +1341,7 @@ class float_type_checker : private ErrorHandler {
FMT_CONSTEXPR void on_general() {}
FMT_CONSTEXPR void on_exp() {}
FMT_CONSTEXPR void on_fixed() {}
FMT_CONSTEXPR void on_percent() {}
FMT_CONSTEXPR void on_hex() {}

FMT_CONSTEXPR void on_error() {
Expand Down Expand Up @@ -2642,17 +2646,20 @@ template <typename Range> class basic_writer {

struct inf_or_nan_writer {
char sign;
bool as_percentage;
const char* str;

size_t size() const {
return static_cast<std::size_t>(INF_SIZE + (sign ? 1 : 0));
return static_cast<std::size_t>(INF_SIZE + (sign ? 1 : 0) +
(as_percentage ? 1 : 0));
}
size_t width() const { return size(); }

template <typename It> void operator()(It&& it) const {
if (sign) *it++ = static_cast<char_type>(sign);
it = internal::copy_str<char_type>(
str, str + static_cast<std::size_t>(INF_SIZE), it);
if (as_percentage) *it++ = static_cast<char_type>('%');
}
};

Expand Down Expand Up @@ -2810,8 +2817,9 @@ struct float_spec_handler {
char type;
bool upper;
bool fixed;
bool as_percentage;

explicit float_spec_handler(char t) : type(t), upper(false), fixed(false) {}
explicit float_spec_handler(char t) : type(t), upper(false), fixed(false), as_percentage(false) {}

void on_general() {
if (type == 'G') upper = true;
Expand All @@ -2826,6 +2834,11 @@ struct float_spec_handler {
if (type == 'F') upper = true;
}

void on_percent() {
fixed = true;
as_percentage = true;
}

void on_hex() {
if (type == 'A') upper = true;
}
Expand Down Expand Up @@ -2854,10 +2867,11 @@ void basic_writer<Range>::write_double(T value, const format_specs& spec) {
basic_writer& writer;
format_specs spec;
char sign;
bool as_percentage;
void operator()(const char* str) const {
writer.write_padded(spec, inf_or_nan_writer{sign, str});
writer.write_padded(spec, inf_or_nan_writer{sign, as_percentage, str});
}
} write_inf_or_nan = {*this, spec, sign};
} write_inf_or_nan = {*this, spec, sign, handler.as_percentage};

// Format NaN and ininity ourselves because sprintf's output is not consistent
// across platforms.
Expand All @@ -2869,11 +2883,19 @@ void basic_writer<Range>::write_double(T value, const format_specs& spec) {
memory_buffer buffer;
int exp = 0;
int precision = spec.has_precision() || !spec.type ? spec.precision : 6;

if (handler.as_percentage) value *= 100.;

bool use_grisu = fmt::internal::use_grisu<T>() &&
(!spec.type || handler.fixed) &&
internal::grisu2_format(static_cast<double>(value), buffer,
precision, handler.fixed, exp);
if (!use_grisu) internal::sprintf_format(value, buffer, spec);

if (handler.as_percentage) {
buffer.push_back('%');
--exp; // Adjust decimal place position.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be -= 2?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The decimal place position is shifted by one place because only one character, the percent sign, is added.

}
align_spec as = spec;
if (spec.align() == ALIGN_NUMERIC) {
if (sign) {
Expand Down
11 changes: 10 additions & 1 deletion test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1207,6 +1207,8 @@ TEST(FormatterTest, Precision) {
"precision not allowed for this argument type");
EXPECT_THROW_MSG(format("{0:.2f}", 42ull), format_error,
"precision not allowed for this argument type");
EXPECT_THROW_MSG(format("{0:.2%}", 42), format_error,
"precision not allowed for this argument type");
EXPECT_THROW_MSG(format("{0:3.0}", 'x'), format_error,
"precision not allowed for this argument type");
EXPECT_EQ("1.2", format("{0:.2}", 1.2345));
Expand Down Expand Up @@ -1440,10 +1442,11 @@ TEST(FormatterTest, FormatConvertibleToLongLong) {

TEST(FormatterTest, FormatFloat) {
EXPECT_EQ("392.500000", format("{0:f}", 392.5f));
EXPECT_EQ("12.500000%", format("{0:%}", 0.125f));
}

TEST(FormatterTest, FormatDouble) {
check_unknown_types(1.2, "eEfFgGaA", "double");
check_unknown_types(1.2, "eEfFgGaA%", "double");
EXPECT_EQ("0.0", format("{:}", 0.0));
EXPECT_EQ("0.000000", format("{:f}", 0.0));
EXPECT_EQ("0", format("{:g}", 0.0));
Expand All @@ -1452,6 +1455,8 @@ TEST(FormatterTest, FormatDouble) {
EXPECT_EQ("392.65", format("{:G}", 392.65));
EXPECT_EQ("392.650000", format("{:f}", 392.65));
EXPECT_EQ("392.650000", format("{:F}", 392.65));
EXPECT_EQ("12.500000%", format("{:%}", 0.125));
EXPECT_EQ("12.34%", format("{:.2%}", 0.1234432));
char buffer[BUFFER_SIZE];
safe_sprintf(buffer, "%e", 392.65);
EXPECT_EQ(buffer, format("{0:e}", 392.65));
Expand All @@ -1473,6 +1478,7 @@ TEST(FormatterTest, FormatNaN) {
EXPECT_EQ("nan ", format("{:<7}", nan));
EXPECT_EQ(" nan ", format("{:^7}", nan));
EXPECT_EQ(" nan", format("{:>7}", nan));
EXPECT_EQ("nan%", format("{:%}", nan));
}

TEST(FormatterTest, FormatInfinity) {
Expand All @@ -1485,6 +1491,7 @@ TEST(FormatterTest, FormatInfinity) {
EXPECT_EQ("inf ", format("{:<7}", inf));
EXPECT_EQ(" inf ", format("{:^7}", inf));
EXPECT_EQ(" inf", format("{:>7}", inf));
EXPECT_EQ("inf%", format("{:%}", inf));
}

TEST(FormatterTest, FormatLongDouble) {
Expand All @@ -1495,6 +1502,8 @@ TEST(FormatterTest, FormatLongDouble) {
EXPECT_EQ("392.65", format("{0:G}", 392.65l));
EXPECT_EQ("392.650000", format("{0:f}", 392.65l));
EXPECT_EQ("392.650000", format("{0:F}", 392.65l));
EXPECT_EQ("12.500000%", format("{:%}", 0.125l));
EXPECT_EQ("12.34%", format("{:.2%}", 0.1234432l));
char buffer[BUFFER_SIZE];
safe_sprintf(buffer, "%Le", 392.65l);
EXPECT_EQ(buffer, format("{0:e}", 392.65l));
Expand Down