From b21460981d35ede84fd5192c6bbae3b654476e86 Mon Sep 17 00:00:00 2001 From: Marcus Elg Date: Wed, 24 Aug 2022 15:41:31 +0200 Subject: Improve string formatting for %f and %v for inf and nan --- core/string/ustring.cpp | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'core/string') diff --git a/core/string/ustring.cpp b/core/string/ustring.cpp index 0c43ba9ccc..aeddf79781 100644 --- a/core/string/ustring.cpp +++ b/core/string/ustring.cpp @@ -4637,15 +4637,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 { @@ -4695,14 +4698,19 @@ String String::sprintf(const Array &values, bool *error) const { String str = "("; for (int i = 0; i < count; i++) { double val = vec[i]; + String number_str = String::num(ABS(val), min_decimals); + bool not_numeric = isinf(val) || isnan(val); + // Pad decimals out. - String number_str = String::num(ABS(val), min_decimals).pad_decimals(min_decimals); + if (!not_numeric) { + number_str = number_str.pad_decimals(min_decimals); + } int initial_len = number_str.length(); // Padding. Leave room for sign later if required. int pad_chars_count = val < 0 ? 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) { number_str = number_str.rpad(pad_chars_count, pad_char); } else { -- cgit v1.2.3