diff options
author | Maganty Rushyendra <mrushyendra@yahoo.com.sg> | 2020-06-03 19:47:47 +0800 |
---|---|---|
committer | Maganty Rushyendra <mrushyendra@yahoo.com.sg> | 2020-06-03 21:21:27 +0800 |
commit | b7d835d9cae8625fe32fa837bae6f3e7843f50e7 (patch) | |
tree | 10a69140af95e6116087144f3d20b92ef9e0328b /core/ustring.cpp | |
parent | 901832e21c74d20689cd59a3464581467997e57c (diff) | |
download | redot-engine-b7d835d9cae8625fe32fa837bae6f3e7843f50e7.tar.gz |
Enable zero padding with float specifier for format strings
Godot currently supports zero padding for integers, octals and
hexadecimals when using format strings, but not for floats.
This commit adds support for zero padding for floats, thus ensuring
consistent behavior for all types, and making Godot's format specifiers'
behavior closer to c's `printf()`.
Before: `print("<%07.2f>" % -0.2345)` prints `< -0.23>`.
Now: `print("<%07.2f>" % -0.2345)` prints `<-000.23>`.
`print("<%7.2f>" % -0.2345)` prints `< -0.23>`.
Diffstat (limited to 'core/ustring.cpp')
-rw-r--r-- | core/ustring.cpp | 31 |
1 files changed, 22 insertions, 9 deletions
diff --git a/core/ustring.cpp b/core/ustring.cpp index cfb547742a..079f18d202 100644 --- a/core/ustring.cpp +++ b/core/ustring.cpp @@ -4143,27 +4143,40 @@ String String::sprintf(const Array &values, bool *error) const { } double value = values[value_index]; - String str = String::num(value, min_decimals); + bool is_negative = (value < 0); + String str = String::num(abs(value), min_decimals); // Pad decimals out. str = str.pad_decimals(min_decimals); - // Show sign - if (show_sign && str.left(1) != "-") { - str = str.insert(0, "+"); - } + int initial_len = str.length(); - // Padding + // 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_zeroes ? String("0") : String(" "); if (left_justified) { - str = str.rpad(min_chars); + if (pad_with_zeroes) { + return "left justification cannot be used with zeros as the padding"; + } else { + str = str.rpad(pad_chars_count, pad_char); + } } else { - str = str.lpad(min_chars); + str = str.lpad(pad_chars_count, pad_char); + } + + // Add sign if needed. + if (show_sign || is_negative) { + String sign_char = is_negative ? "-" : "+"; + if (left_justified) { + str = str.insert(0, sign_char); + } else { + str = str.insert(pad_with_zeroes ? 0 : str.length() - initial_len, sign_char); + } } formatted += str; ++value_index; in_format = false; - break; } case 's': { // String |