Merge pull request #39261 from mrushyendra/string_padding
Enable zero padding with float specifier for format strings
This commit is contained in:
commit
786fc63faa
1 changed files with 23 additions and 10 deletions
|
@ -4143,27 +4143,40 @@ String String::sprintf(const Array &values, bool *error) const {
|
||||||
}
|
}
|
||||||
|
|
||||||
double value = values[value_index];
|
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.
|
// Pad decimals out.
|
||||||
str = str.pad_decimals(min_decimals);
|
str = str.pad_decimals(min_decimals);
|
||||||
|
|
||||||
// Show sign
|
int initial_len = str.length();
|
||||||
if (show_sign && str.left(1) != "-") {
|
|
||||||
str = str.insert(0, "+");
|
// 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) {
|
||||||
|
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(pad_chars_count, pad_char);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Padding
|
// Add sign if needed.
|
||||||
if (left_justified) {
|
if (show_sign || is_negative) {
|
||||||
str = str.rpad(min_chars);
|
String sign_char = is_negative ? "-" : "+";
|
||||||
} else {
|
if (left_justified) {
|
||||||
str = str.lpad(min_chars);
|
str = str.insert(0, sign_char);
|
||||||
|
} else {
|
||||||
|
str = str.insert(pad_with_zeroes ? 0 : str.length() - initial_len, sign_char);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
formatted += str;
|
formatted += str;
|
||||||
++value_index;
|
++value_index;
|
||||||
in_format = false;
|
in_format = false;
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 's': { // String
|
case 's': { // String
|
||||||
|
|
Loading…
Reference in a new issue