diff --git a/src/core/IronPython/Runtime/FloatFormatter.cs b/src/core/IronPython/Runtime/FloatFormatter.cs index 377c2ab80..b930643f9 100644 --- a/src/core/IronPython/Runtime/FloatFormatter.cs +++ b/src/core/IronPython/Runtime/FloatFormatter.cs @@ -26,8 +26,9 @@ internal static class FloatFormatter { /// /// Formats the absolute value of ; the caller is responsible for the sign. /// - /// One of e, E, f, F, g or G. - public static string Format(double value, char type, int precision, bool altForm = false) { + /// One of e, E, f, F, g, G or r (repr, is ignored). + /// Append ".0" to integral fixed-point results (Py_DTSF_ADD_DOT_0). + public static string Format(double value, char type, int precision, bool altForm = false, bool addDot0 = false) { Debug.Assert(precision >= 0); value = Math.Abs(value); @@ -51,7 +52,15 @@ public static string Format(double value, char type, int precision, bool altForm } case 'g': case 'G': - return FormatGeneral(value, precision, altForm, upper); + return FormatGeneral(value, precision, altForm, addDot0, upper); + case 'r': { + string res = Schubfach.dtoa(value, addDot0); + if (altForm && !res.Contains('.')) { + int idx = res.IndexOf('e'); + res = idx == -1 ? res + "." : res.Insert(idx, "."); + } + return res; + } default: throw new ArgumentOutOfRangeException(nameof(type)); } @@ -61,12 +70,12 @@ public static string Format(double value, char type, int precision, bool altForm /// Rounds to significant digits and uses exponent notation if the exponent is below -4 or at least the precision. /// Trailing zeros are removed unless is set. /// - private static string FormatGeneral(double value, int precision, bool altForm, bool upper) { + private static string FormatGeneral(double value, int precision, bool altForm, bool addDot0, bool upper) { if (precision == 0) precision = 1; string mantissa = FormatSignificant(value, precision, out int exp); - if (exp < -4 || exp >= precision) { + if (exp < -4 || exp >= (addDot0 ? precision - 1 : precision)) { if (!altForm) mantissa = TrimFraction(mantissa); else if (precision == 1) mantissa += "."; return mantissa + FormatExponent(exp, upper); @@ -85,6 +94,7 @@ private static string FormatGeneral(double value, int precision, bool altForm, b if (fraction.Length > 0) return intPart + "." + fraction; if (altForm) return intPart + "."; + if (addDot0) return intPart + ".0"; return intPart; static string TrimFraction(string mantissa) @@ -197,5 +207,62 @@ private static string RoundDigits(string digits, int keep) { } return res.ToString(); } + + private static readonly int[] DefaultGroupSizes = [3]; + + public static string AddGrouping(string digits, string separator, int minWidth = 0) + => AddGrouping(digits, separator, DefaultGroupSizes, minWidth); + + /// + /// Inserts into the leading run of digits, zero padding it so the result is at least long. + /// + /// As in : the last size repeats and 0 ends grouping. + public static string AddGrouping(string digits, string separator, int[] groupSizes, int minWidth = 0) { + int end = 0; + while (end < digits.Length && char.IsDigit(digits[end])) end++; + if (end == 0) return digits; + + // zero pad the integer part until the grouped result is wide enough + int tailLength = digits.Length - end; + int count = end; + int intLength = GroupedLength(ref count, minWidth - tailLength); + string intPart = digits.Substring(0, end).PadLeft(count, '0'); + + // copy groups from the right, with a separator in front of each one except the leftmost + var res = new char[intLength + tailLength]; + digits.CopyTo(end, res, intLength, tailLength); + int pos = intLength; + int i = count; + for (int k = 0; ; k++) { + int size = GroupSize(groupSizes, k); + if (size == 0 || size >= i) break; + i -= size; + pos -= size; + intPart.CopyTo(i, res, pos, size); + pos -= separator.Length; + separator.CopyTo(0, res, pos, separator.Length); + } + Debug.Assert(pos == i); + intPart.CopyTo(0, res, 0, i); + return new string(res); + + // grows digitCount (zero padding) until the grouped length is at least minWidth, returns that length + int GroupedLength(ref int digitCount, int minWidth) { + int placed = 0, length = 0; + for (int k = 0; ; k++) { + int size = GroupSize(groupSizes, k); + int last = Math.Max(Math.Max(digitCount - placed, minWidth - length), 1); + if (size == 0 || size >= last) { + digitCount = placed + last; + return length + last; + } + placed += size; + length += size + separator.Length; + } + } + } + + private static int GroupSize(int[] groupSizes, int k) + => groupSizes.Length == 0 ? 0 : groupSizes[Math.Min(k, groupSizes.Length - 1)]; } } diff --git a/src/core/IronPython/Runtime/Operations/BigIntegerOps.cs b/src/core/IronPython/Runtime/Operations/BigIntegerOps.cs index bee93c914..500b2c0bc 100644 --- a/src/core/IronPython/Runtime/Operations/BigIntegerOps.cs +++ b/src/core/IronPython/Runtime/Operations/BigIntegerOps.cs @@ -798,7 +798,7 @@ public static BigInteger ToBigInteger(BigInteger self) { case 'F': case 'g': case 'G': - digits = DoubleOps.DoubleToFormatString(context, ToDouble(val), spec); + digits = DoubleOps.DoubleToFormatString(context, ToDouble(self), spec); break; case 'X': if (spec.Precision != null) { diff --git a/src/core/IronPython/Runtime/Operations/ComplexOps.cs b/src/core/IronPython/Runtime/Operations/ComplexOps.cs index b6564759d..396eb003a 100644 --- a/src/core/IronPython/Runtime/Operations/ComplexOps.cs +++ b/src/core/IronPython/Runtime/Operations/ComplexOps.cs @@ -270,36 +270,32 @@ public static string __repr__(CodeContext/*!*/ context, Complex x) { public static string __format__(CodeContext/*!*/ context, Complex self, string formatSpec) { StringFormatSpec spec = StringFormatSpec.FromString(formatSpec); - if (spec.AlignmentIsZeroPad) throw PythonOps.ValueError("Zero padding is not allowed in complex format specifier"); + bool hasType = spec.Type is not (null or '\0'); + if (hasType && spec.Type is not ('e' or 'E' or 'f' or 'F' or 'g' or 'G' or 'n')) throw PythonOps.ValueError("Unknown format code '{0}' for object of type 'complex'", spec.TypeRepr); + if (spec.Fill == '0') throw PythonOps.ValueError("Zero padding is not allowed in complex format specifier"); if (spec.Alignment == '=') throw PythonOps.ValueError("'=' alignment flag is not allowed in complex format specifier"); - var sb = new StringBuilder(); - if (spec.AlternateForm) sb.Append('#'); - if (spec.ThousandsComma) sb.Append(','); - if (spec.Precision.HasValue) { - sb.Append('.'); - sb.Append(spec.Precision.Value); - } - sb.Append(spec.Type ?? 'g'); - var numberformat = sb.ToString(); - string res; - if (!spec.Type.HasValue) { - if (self.Real == 0) { - res = DoubleOps.__format__(context, self.Imaginary, spec.Sign.HasValue ? spec.Sign.Value + numberformat : numberformat) + "j"; + if (!hasType) { + if (self.Real == 0 && !DoubleOps.IsNegativeZero(self.Real)) { + res = FormatPart(self.Imaginary, imag: false) + "j"; } else { - var real = DoubleOps.__format__(context, self.Real, spec.Sign.HasValue ? spec.Sign.Value + numberformat : numberformat); - var imag = DoubleOps.__format__(context, self.Imaginary, "+" + numberformat); - res = "(" + real + imag + "j)"; + res = "(" + FormatPart(self.Real, imag: false) + FormatPart(self.Imaginary, imag: true) + "j)"; } } else { - var real = DoubleOps.__format__(context, self.Real, spec.Sign.HasValue ? spec.Sign.Value + numberformat : numberformat); - var imag = DoubleOps.__format__(context, self.Imaginary, "+" + numberformat); - res = real + imag + "j"; + res = FormatPart(self.Real, imag: false) + FormatPart(self.Imaginary, imag: true) + "j"; } if (spec.Width is null) return res; return StringOps.__format__(context, res, $"{spec.Fill ?? ' '}{spec.Alignment ?? '>'}{spec.Width}s"); + + string FormatPart(double value, bool imag) { + string digits = DoubleOps.DoubleToFormatString(context, value, spec, addDot0: false); + if (!double.IsNaN(value) && DoubleOps.Sign(value) < 0) return "-" + digits; + if (imag || spec.Sign == '+') return "+" + digits; + if (spec.Sign == ' ') return " " + digits; + return digits; + } } // report the same errors as CPython for these invalid conversions diff --git a/src/core/IronPython/Runtime/Operations/FloatOps.cs b/src/core/IronPython/Runtime/Operations/FloatOps.cs index c8c52737f..91ad88d26 100644 --- a/src/core/IronPython/Runtime/Operations/FloatOps.cs +++ b/src/core/IronPython/Runtime/Operations/FloatOps.cs @@ -768,195 +768,59 @@ public static string __format__(CodeContext/*!*/ context, double self, [NotNone] if (formatSpec == string.Empty) return __str__(context, self); StringFormatSpec spec = StringFormatSpec.FromString(formatSpec); - string digits; + string digits = DoubleToFormatString(context, self, spec); - if (Double.IsPositiveInfinity(self) || Double.IsNegativeInfinity(self)) { - if (spec.Type != null && char.IsUpper(spec.Type.Value)) { - digits = "INF"; - } else { - digits = "inf"; - } - } else if (Double.IsNaN(self)) { - if (spec.Type != null && char.IsUpper(spec.Type.Value)) { - digits = "NAN"; - } else { - digits = "nan"; - } - } else { - digits = DoubleToFormatString(context, self, spec); - } - - if (spec.Sign == null) { - // This is special because its not "-nan", it's nan. - // Always pass isZero=false so that -0.0 shows up - return spec.AlignNumericText(digits, false, Double.IsNaN(self) || Sign(self) > 0); - } else { - // Always pass isZero=false so that -0.0 shows up - return spec.AlignNumericText(digits, false, Double.IsNaN(self) ? true : Sign(self) > 0); - } + // nan never gets a "-"; isZero is false so that -0.0 keeps its sign + return spec.AlignNumericText(digits, false, Double.IsNaN(self) || Sign(self) > 0); } /// /// Returns the digits for the format spec, no sign is included. /// - internal static string DoubleToFormatString(CodeContext/*!*/ context, double self, StringFormatSpec/*!*/ spec) { - self = Math.Abs(self); + /// Without a type, append ".0" to integral values like str() does. + internal static string DoubleToFormatString(CodeContext/*!*/ context, double self, StringFormatSpec/*!*/ spec, bool addDot0 = true) { const int DefaultPrecision = 6; int precision = spec.Precision ?? DefaultPrecision; + int minWidth = spec.Fill == '0' && spec.Alignment == '=' && spec.Width is { } width ? ((spec.Sign != null && spec.Sign != '-' || Sign(self) < 0) ? width - 1 : width) : 0; string digits; switch (spec.Type) { - case '%': { - string fmt = "0." + new string('0', precision) + "%"; - if (spec.ThousandsComma) { - fmt = "#," + fmt; - } - digits = self.ToString(fmt, CultureInfo.InvariantCulture); - break; - } - case 'f': - case 'F': { - string fmt = "0." + new string('0', precision); - if (spec.ThousandsComma) { - fmt = "#," + fmt; - } - digits = self.ToString(fmt, CultureInfo.InvariantCulture); - break; - } + case '%': + digits = FloatFormatter.Format(self * 100, 'f', precision, spec.AlternateForm) + "%"; + break; case 'e': - case 'E': { - string fmt = "0." + new string('0', precision) + spec.Type + "+00"; - if (spec.ThousandsComma) { - fmt = "#," + fmt; - } - digits = self.ToString(fmt, CultureInfo.InvariantCulture); - break; - } - case '\0': - case null: - if (spec.Precision != null) { - // precision applies to the combined digits before and after the decimal point - // so we first need find out how many digits we have before... - int digitCnt = 1; - double cur = self; - while (cur >= 10) { - cur /= 10; - digitCnt++; - } - - // Use exponents if we don't have enough room for all the digits before. If we - // only have as single digit avoid exponents. - if (digitCnt > spec.Precision.Value && digitCnt != 1) { - // first round off the decimal value - self = MathUtils.Round(self, 0 , MidpointRounding.ToEven); - - // then remove any insignificant digits - double pow = Math.Pow(10, digitCnt - Math.Max(spec.Precision.Value, 1)); - self = self - (self % pow); - - // finally format w/ the requested precision - string fmt = "0.0" + new string('#', spec.Precision.Value); - - digits = self.ToString(fmt + "e+00", CultureInfo.InvariantCulture); - } else { - // we're including all the numbers to the right of the decimal we can, we explicitly - // round to match CPython's behavior - int decimalPoints = Math.Max(spec.Precision.Value - digitCnt, 0); - - self = MathUtils.Round(self, decimalPoints, MidpointRounding.ToEven); - digits = self.ToString("0.0" + new string('#', decimalPoints), CultureInfo.InvariantCulture); - } - } else { - // just the default formatting - if (IncludeExponent(self)) { - digits = self.ToString("0.#e+00", CultureInfo.InvariantCulture); - } else if (spec.ThousandsComma) { - digits = self.ToString("#,0.0###", CultureInfo.InvariantCulture); - } else { - digits = self.ToString("0.0###", CultureInfo.InvariantCulture); - } - } + case 'E': + case 'f': + case 'F': + case 'g': + case 'G': + digits = FloatFormatter.Format(self, spec.Type.Value, precision, spec.AlternateForm); break; case 'n': - case 'g': - case 'G': { - // precision applies to the combined digits before and after the decimal point - // so we first need find out how many digits we have before... - int digitCnt = 1; - double cur = self; - while (cur >= 10) { - cur /= 10; - digitCnt++; - } - - // Use exponents if we don't have enough room for all the digits before. If we - // only have as single digit avoid exponents. - if (digitCnt > precision && digitCnt != 1) { - // first round off the decimal value - self = MathUtils.Round(self, 0, MidpointRounding.ToEven); - - // then remove any insignificant digits - double pow = Math.Pow(10, digitCnt - Math.Max(precision, 1)); - double rest = self / pow; - self = self - self % pow; - if ((rest % 1) >= .5) { - // round up - self += pow; - } - - string fmt; - if (spec.Precision > 1 || digitCnt > 6) { - // include the requested precision to the right of the decimal - fmt = "0.#" + new string('#', precision); - } else { - // zero precision, no decimal - fmt = "0"; - } - if (spec.ThousandsComma) { - fmt = "#," + fmt; - } - - digits = self.ToString(fmt + (spec.Type == 'G' ? "E+00" : "e+00"), CultureInfo.InvariantCulture); - } else { - // we're including all the numbers to the right of the decimal we can, we explicitly - // round to match CPython's behavior - if (self < 1) { - // no implicit 0 - digitCnt--; - } - int decimalPoints = Math.Max(precision - digitCnt, 0); - - self = MathUtils.Round(self, decimalPoints, MidpointRounding.ToEven); - - if (spec.Type == 'n' && context.LanguageContext.NumericCulture != PythonContext.CCulture) { - if (digitCnt != precision && (self % 1) != 0) { - digits = self.ToString("#,0.0" + new string('#', decimalPoints), context.LanguageContext.NumericCulture); - } else { - // leave out the decimal if the precision == # of digits or we have a whole number - digits = self.ToString("#,0", context.LanguageContext.NumericCulture); - } - } else { - if (digitCnt != precision && (self % 1) != 0) { - digits = self.ToString("0.0" + new string('#', decimalPoints), CultureInfo.InvariantCulture); - } else { - // leave out the decimal if the precision == # of digits or we have a whole number - digits = self.ToString("0", CultureInfo.InvariantCulture); - } - } - } + digits = FloatFormatter.Format(self, 'g', precision, spec.AlternateForm); + CultureInfo culture = context.LanguageContext.NumericCulture; + if (culture != PythonContext.CCulture) { + NumberFormatInfo nfi = culture.NumberFormat; + digits = digits.Replace(".", nfi.NumberDecimalSeparator); + digits = FloatFormatter.AddGrouping(digits, nfi.NumberGroupSeparator, nfi.NumberGroupSizes, minWidth); } + return digits; + case '\0': + case null: + digits = FloatFormatter.Format(self, spec.Precision.HasValue ? 'g' : 'r', precision, spec.AlternateForm, addDot0); break; default: throw PythonOps.ValueError("Unknown format code '{0}' for object of type 'float'", spec.TypeRepr); } + if (spec.ThousandsComma) { + digits = FloatFormatter.AddGrouping(digits, ",", minWidth); + } else if (spec.ThousandsUnderscore) { + digits = FloatFormatter.AddGrouping(digits, "_", minWidth); + } return digits; } - private static bool IncludeExponent(double self) { - return self >= 1e12 || (self != 0 && self <= 0.00009); - } - private static string DefaultFloatFormat() { if (BitConverter.IsLittleEndian) { return "IEEE, little-endian"; diff --git a/src/core/IronPython/Runtime/Operations/IntOps.cs b/src/core/IronPython/Runtime/Operations/IntOps.cs index a4698a642..afdc30225 100644 --- a/src/core/IronPython/Runtime/Operations/IntOps.cs +++ b/src/core/IronPython/Runtime/Operations/IntOps.cs @@ -261,7 +261,7 @@ public static string __format__(CodeContext/*!*/ context, int self, [NotNone] st case 'F': case 'g': case 'G': - digits = DoubleOps.DoubleToFormatString(context, val, spec); + digits = DoubleOps.DoubleToFormatString(context, self, spec); break; case 'X': if (spec.Precision != null) { diff --git a/src/core/IronPython/Runtime/StringFormatSpec.cs b/src/core/IronPython/Runtime/StringFormatSpec.cs index 1a9b5b01c..804738de1 100644 --- a/src/core/IronPython/Runtime/StringFormatSpec.cs +++ b/src/core/IronPython/Runtime/StringFormatSpec.cs @@ -17,9 +17,9 @@ namespace IronPython.Runtime { /// Provides a representation and parsing for the default formatting specification. This is used /// by object.__format__, int.__format__, long.__format__, and float.__format__ to do the common /// format spec parsing. - /// + /// /// The default specification is: - /// + /// /// format_spec = [[fill]align][sign][#][0][width][,][.precision][type] /// fill = a character other than } /// align = "<" | ">" | "=" | "^" @@ -33,9 +33,8 @@ internal class StringFormatSpec { internal readonly int? Width, Precision; internal readonly bool AlternateForm, ThousandsComma, ThousandsUnderscore; internal readonly bool IsEmpty; - internal readonly bool AlignmentIsZeroPad; - private StringFormatSpec(char? fill, char? alignment, char? sign, int? width, bool thousandsComma, bool thousandsUnderscore, int? precision, char? type, bool alternateForm, bool isEmpty, bool alignmentIsZeroPad) { + private StringFormatSpec(char? fill, char? alignment, char? sign, int? width, bool thousandsComma, bool thousandsUnderscore, int? precision, char? type, bool alternateForm, bool isEmpty) { Fill = fill; Alignment = alignment; Sign = sign; @@ -46,7 +45,6 @@ private StringFormatSpec(char? fill, char? alignment, char? sign, int? width, bo Type = type; AlternateForm = alternateForm; IsEmpty = isEmpty; - AlignmentIsZeroPad = alignmentIsZeroPad; } internal string TypeRepr => (0x20 < Type && Type < 0x80) ? Type.ToString() : $"\\x{(int)Type:x}"; @@ -62,32 +60,16 @@ private StringFormatSpec(char? fill, char? alignment, char? sign, int? width, bo bool alternateForm = false, thousandsComma = false; bool thousandsUnderscore = false; bool isEmpty = formatSpec.Length == 0; - bool alignmentIsZeroPad = false; int curOffset = 0; - if (formatSpec.Length >= 2) { - // check 2nd character for alignment first, then 1st character - switch (formatSpec[1]) { - case '<': - case '>': - case '=': - case '^': - fill = formatSpec[0]; - align = formatSpec[1]; - curOffset = 2; - break; - default: - switch (formatSpec[0]) { - case '<': - case '>': - case '=': - case '^': - align = formatSpec[0]; - curOffset = 1; - break; - } - break; - } + // check 2nd character for alignment first, then 1st character + if (formatSpec.Length >= 2 && IsAlignment(formatSpec[1])) { + fill = formatSpec[0]; + align = formatSpec[1]; + curOffset = 2; + } else if (formatSpec.Length >= 1 && IsAlignment(formatSpec[0])) { + align = formatSpec[0]; + curOffset = 1; } // read sign @@ -111,10 +93,7 @@ private StringFormatSpec(char? fill, char? alignment, char? sign, int? width, bo if (align == null) { align = '='; } - if (fill == null) { - fill = '0'; - alignmentIsZeroPad = true; - } + fill ??= '0'; curOffset++; } @@ -137,7 +116,7 @@ private StringFormatSpec(char? fill, char? alignment, char? sign, int? width, bo thousandsUnderscore = true; curOffset++; if (thousandsComma || curOffset != formatSpec.Length && formatSpec[curOffset] == ',') { - throw PythonOps.ValueError("Cannot specify both ',' and '_'"); + throw PythonOps.ValueError("Cannot specify both ',' and '_'."); } } @@ -177,7 +156,7 @@ private StringFormatSpec(char? fill, char? alignment, char? sign, int? width, bo case '%': break; default: - throw PythonOps.ValueError("Cannot specify ',' with '{0}'", type); + throw PythonOps.ValueError("Cannot specify ',' with '{0}'.", type); } } else if (thousandsUnderscore) { switch (type) { @@ -198,7 +177,7 @@ private StringFormatSpec(char? fill, char? alignment, char? sign, int? width, bo case '%': break; default: - throw PythonOps.ValueError("Cannot specify '_' with '{0}'", type); + throw PythonOps.ValueError("Cannot specify '_' with '{0}'.", type); } } } @@ -217,9 +196,10 @@ private StringFormatSpec(char? fill, char? alignment, char? sign, int? width, bo precision, type, alternateForm, - isEmpty, - alignmentIsZeroPad + isEmpty ); + + static bool IsAlignment(char c) => c is '<' or '>' or '=' or '^'; } internal string/*!*/ AlignText(string/*!*/ text) { @@ -324,7 +304,7 @@ private StringFormatSpec(char? fill, char? alignment, char? sign, int? width, bo text = FinishText(text, sign, type); } - + return text; } diff --git a/tests/suite/stdlib/test_complex.py b/tests/suite/stdlib/test_complex.py index 5b0de9052..06dabd264 100644 --- a/tests/suite/stdlib/test_complex.py +++ b/tests/suite/stdlib/test_complex.py @@ -16,9 +16,7 @@ def load_tests(loader, standard_tests, pattern): tests = loader.loadTestsFromModule(test.test_complex, pattern=pattern) if is_ironpython: - failing_tests = [ - test.test_complex.ComplexTest('test_format'), - ] + failing_tests = [] if sys.version_info >= (3, 6): failing_tests += [ test.test_complex.ComplexTest('test_underscores'), # https://github.com/IronLanguages/ironpython3/issues/105 diff --git a/tests/suite/stdlib/test_float.py b/tests/suite/stdlib/test_float.py index 43774a7b8..39b51f5eb 100644 --- a/tests/suite/stdlib/test_float.py +++ b/tests/suite/stdlib/test_float.py @@ -17,8 +17,6 @@ def load_tests(loader, standard_tests, pattern): if is_ironpython: failing_tests = [ - test.test_float.FormatTestCase('test_format'), - test.test_float.FormatTestCase('test_issue5864'), test.test_float.InfNanTest('test_nan_signs'), test.test_float.RoundTestCase('test_large_n'), test.test_float.RoundTestCase('test_matches_float_format'), diff --git a/tests/suite/stdlib/test_types.py b/tests/suite/stdlib/test_types.py index f1e5ff2c7..e03c0d1ed 100644 --- a/tests/suite/stdlib/test_types.py +++ b/tests/suite/stdlib/test_types.py @@ -23,7 +23,6 @@ def load_tests(loader, standard_tests, pattern): test.test_types.MappingProxyTests('test_missing'), # AssertionError: 'missing=y' != None test.test_types.SimpleNamespaceTests('test_attrdel'), # KeyError: spam test.test_types.SimpleNamespaceTests('test_pickle'), # TypeError: protocol 0 - test.test_types.TypesTests('test_float__format__'), # AssertionError: '1.12339e+200' != '1.1234e+200' test.test_types.TypesTests('test_internal_sizes'), # AttributeError: 'type' object has no attribute '__basicsize__' ] if sys.version_info >= (3, 6): diff --git a/tests/suite/test_strformat.py b/tests/suite/test_strformat.py index 1a7a4c5bd..fc1a6ffe9 100644 --- a/tests/suite/test_strformat.py +++ b/tests/suite/test_strformat.py @@ -317,50 +317,27 @@ def test_str___format___errors(self): def test_float___format__(self): tests = [] - if is_cpython: #In large part due to http://ironpython.codeplex.com/workitem/28206 - tests+= [ (2.0, '6.1', ' 2e+00'), - (2.5, '6.1', ' 2e+00'), - (2.25, '6.1', ' 2e+00'), - (23.0, '.1', '2e+01'), - (23.0, '.2', '2.3e+01'), - (230.5, '.3', '2.3e+02'), - (11230.54, '.5', '1.1231e+04'), - (111230.54, '.1', '1e+05'), - (100000.0, '.5', '1e+05'), - (0.0, '1.1', '0e+00'), - (0.0, '1.0', '0e+00'), - (1.0, '.0', '1e+00'), - (1.1, '.0', '1e+00'), - (1.1, '.1', '1e+00'), - (10.0, '.1', '1e+01'), - (10.0, '.0', '1e+01'), - (1000000000.12, '1.10', '1e+09'), - (1000000000.12, '1.3', '1e+09'), - (999999999999.9, '1.0', '1e+12'), - (999999999999.9, '1.2', '1e+12'), - ] - else: - tests+= [ (2.0, '6.1', ' 2.0'), - (2.5, '6.1', ' 2.0'), - (2.25, '6.1', ' 2.0'), - (23.0, '.1', '2.0e+01'), - (23.0, '.2', '23.0'), - (230.5, '.3', '230.0'), - (11230.54, '.5', '11231.0'), - (111230.54, '.1', '1.0e+05'), - (100000.0, '.5', '1.0e+05'), - (0.0, '1.1', '0.0'), - (0.0, '1.0', '0.0'), - (1.0, '.0', '1.0'), - (1.1, '.0', '1.0'), - (1.1, '.1', '1.0'), - (10.0, '.1', '1.0e+01'), - (10.0, '.0', '1.0e+01'), - (1000000000.12, '1.10', '1000000000.0'), - (1000000000.12, '1.3', '1.0e+09'), - (999999999999.9, '1.0', '1.0e+12'), - (999999999999.9, '1.2', '1.0e+12'), - ] + tests+= [ (2.0, '6.1', ' 2e+00'), + (2.5, '6.1', ' 2e+00'), + (2.25, '6.1', ' 2e+00'), + (23.0, '.1', '2e+01'), + (23.0, '.2', '2.3e+01'), + (230.5, '.3', '2.3e+02'), + (11230.54, '.5', '1.1231e+04'), + (111230.54, '.1', '1e+05'), + (100000.0, '.5', '1e+05'), + (0.0, '1.1', '0e+00'), + (0.0, '1.0', '0e+00'), + (1.0, '.0', '1e+00'), + (1.1, '.0', '1e+00'), + (1.1, '.1', '1e+00'), + (10.0, '.1', '1e+01'), + (10.0, '.0', '1e+01'), + (1000000000.12, '1.10', '1e+09'), + (1000000000.12, '1.3', '1e+09'), + (999999999999.9, '1.0', '1e+12'), + (999999999999.9, '1.2', '1e+12'), + ] tests+= [ (2.0, '', '2.0'), (2.0, 'g', '2'), @@ -537,6 +514,17 @@ def test_float___format__(self): (10e667, '', 'inf'), (-10e667, '', '-inf'), (10e667/10e667, '', 'nan'), + + # zero padding is grouped too + (1.5, '010,', '0,000,001.5'), + (-1.5, '010,', '-000,001.5'), + (-0.0, '08,', '-0,000.0'), + (1234.5, '0=10,', '0,001,234.5'), + (1234.5, '0<12,', '1,234.500000'), + (1234.5, '012,.1e', '00,001.2e+03'), + (0.5, '012,%', '0,050.000000%'), + (1234567.5, '015,.2f', '0,001,234,567.50'), + (10e667/10e667, '010,', '0000000nan'), ] upper_spec_trans = str.maketrans({"f": "F", "e": "E", "g": "G"}) @@ -552,6 +540,12 @@ def test_float___format__(self): result = result.upper() self.assertEqual(actual, result, "value:{0}, spec:{1}, (expected) result:{2}, actual:{3}, expr:({0}).__format__('{1}')".format(value, upper_spec, result, actual)) + # padding is computed per group, not per character + actual = format(1.5, '01000000,') + self.assertEqual(len(actual), 1000000) + self.assertTrue(actual.startswith('00,000,')) + self.assertTrue(actual.endswith(',000,001.5')) + if is_netcoreapp21: return # https://github.com/IronLanguages/ironpython3/issues/751 # check locale specific formatting @@ -573,6 +567,10 @@ def test_float___format__(self): (100000.5, '.7n', '100,000.5'), (100000.5, 'n', '100,000'), (100000.5, '.6n', '100,000'), + + (1.5, '010n', '0,000,001.5'), + (-1234.5, '012n', '-0,001,234.5'), + (1234.5, '0<12n', '1,234.500000'), ] for value, spec, result in tests: @@ -606,6 +604,19 @@ def test_float___format___errors(self): for value, errorFmt, errorMsg in errors: self.assertRaisesMessage(ValueError, errorMsg, value.__format__, errorFmt) + def test_complex___format___errors(self): + self.assertEqual(format(1+2j, '\0'), '(1+2j)') + for spec, errorMsg in [ + ('%', "Unknown format code '%' for object of type 'complex'"), + ('d', "Unknown format code 'd' for object of type 'complex'"), + ('0%', "Unknown format code '%' for object of type 'complex'"), + ('05', "Zero padding is not allowed in complex format specifier"), + ('0>5', "Zero padding is not allowed in complex format specifier"), + ('0=5', "Zero padding is not allowed in complex format specifier"), + ('=5', "'=' alignment flag is not allowed in complex format specifier"), + ]: + self.assertRaisesMessage(ValueError, errorMsg, format, 1j, spec) + def test_int___format__(self): tests = [ (0, '+', '+0'), @@ -654,6 +665,11 @@ def test_int___format__(self): (-2, 'x^ 9', 'xxx-2xxxx'), (2, '\0^ 9', '\0\0\0 2\0\0\0\0'), + (-1, '08,g', '-000,001'), + (-1, '08,.0%', '-00,100%'), + (-1234,'012,.1f', '-0,001,234.0'), + (-10**20, '030,.0f', '-0,100,000,000,000,000,000,000'), + (2, 'c', '\x02'), (2, '<5c', '\x02 '), (2, '>5c', ' \x02'),