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

[3.x] Improve string formatting (%f) for inf and nan #64870

Merged
merged 1 commit into from
Oct 3, 2022
Merged
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
7 changes: 5 additions & 2 deletions core/ustring.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4339,15 +4339,18 @@ String String::sprintf(const Array &values, bool *error) const {
double value = values[value_index];
bool is_negative = (value < 0);
String str = String::num(ABS(value), min_decimals);
bool not_numeric = isinf(value) || isnan(value);

// Pad decimals out.
str = str.pad_decimals(min_decimals);
if (!not_numeric) {
str = str.pad_decimals(min_decimals);
}

int initial_len = str.length();

// Padding. Leave room for sign later if required.
int pad_chars_count = (is_negative || show_sign) ? min_chars - 1 : min_chars;
String pad_char = pad_with_zeros ? String("0") : String(" ");
String pad_char = (pad_with_zeros && !not_numeric) ? String("0") : String(" "); // Never pad NaN or inf with zeros
if (left_justified) {
str = str.rpad(pad_chars_count, pad_char);
} else {
Expand Down
8 changes: 8 additions & 0 deletions main/tests/test_string.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,14 @@ bool test_28() {
OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL");
state = state && success;

// Real (infinity) left-padded
format = "fish %11f frog";
args.clear();
args.push_back(INFINITY);
output = format.sprintf(args, &error);
success = (output == String("fish inf frog") && !error);
state = state && success;

// Real right-padded
format = "fish %-11f frog";
args.clear();
Expand Down