From 42ff9cf8bcfa912cd69bf65e016d6e1c7ba876b4 Mon Sep 17 00:00:00 2001 From: Relintai Date: Sat, 8 Oct 2022 17:53:43 +0200 Subject: [PATCH] Ported: Improve %f formatting for inf and nan. - MarcusElg https://github.com/godotengine/godot/commit/e9cbe9517be2d8e2f55882f187544bdc4e232170 --- core/string/ustring.cpp | 7 +++++-- main/tests/test_string.cpp.old | 8 ++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/core/string/ustring.cpp b/core/string/ustring.cpp index a4d83a0aa..f6cc98931 100644 --- a/core/string/ustring.cpp +++ b/core/string/ustring.cpp @@ -1774,15 +1774,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 { diff --git a/main/tests/test_string.cpp.old b/main/tests/test_string.cpp.old index 2b6781b90..1eb06d745 100644 --- a/main/tests/test_string.cpp.old +++ b/main/tests/test_string.cpp.old @@ -638,6 +638,14 @@ bool test_28() { OS::get_singleton()->print(output_format, format.get_data(), output.get_data(), 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();