Ported: Improve %f formatting for inf and nan.

- MarcusElg
e9cbe9517b
This commit is contained in:
Relintai 2022-10-08 17:53:43 +02:00
parent 8e301d27ba
commit 42ff9cf8bc
2 changed files with 13 additions and 2 deletions

View File

@ -1774,15 +1774,18 @@ String String::sprintf(const Array &values, bool *error) const {
double value = values[value_index]; double value = values[value_index];
bool is_negative = (value < 0); bool is_negative = (value < 0);
String str = String::num(ABS(value), min_decimals); String str = String::num(ABS(value), min_decimals);
bool not_numeric = isinf(value) || isnan(value);
// Pad decimals out. // Pad decimals out.
if (!not_numeric) {
str = str.pad_decimals(min_decimals); str = str.pad_decimals(min_decimals);
}
int initial_len = str.length(); int initial_len = str.length();
// Padding. Leave room for sign later if required. // Padding. Leave room for sign later if required.
int pad_chars_count = (is_negative || show_sign) ? min_chars - 1 : min_chars; 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) { if (left_justified) {
str = str.rpad(pad_chars_count, pad_char); str = str.rpad(pad_chars_count, pad_char);
} else { } else {

View File

@ -638,6 +638,14 @@ bool test_28() {
OS::get_singleton()->print(output_format, format.get_data(), output.get_data(), success ? "OK" : "FAIL"); OS::get_singleton()->print(output_format, format.get_data(), output.get_data(), success ? "OK" : "FAIL");
state = state && success; 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 // Real right-padded
format = "fish %-11f frog"; format = "fish %-11f frog";
args.clear(); args.clear();