This repository was archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathNumber.Formatting.cs
2539 lines (2209 loc) · 104 KB
/
Number.Formatting.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers.Text;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System
{
// The Format methods provided by the numeric classes convert
// the numeric value to a string using the format string given by the
// format parameter. If the format parameter is null or
// an empty string, the number is formatted as if the string "G" (general
// format) was specified. The info parameter specifies the
// NumberFormatInfo instance to use when formatting the number. If the
// info parameter is null or omitted, the numeric formatting information
// is obtained from the current culture. The NumberFormatInfo supplies
// such information as the characters to use for decimal and thousand
// separators, and the spelling and placement of currency symbols in monetary
// values.
//
// Format strings fall into two categories: Standard format strings and
// user-defined format strings. A format string consisting of a single
// alphabetic character (A-Z or a-z), optionally followed by a sequence of
// digits (0-9), is a standard format string. All other format strings are
// used-defined format strings.
//
// A standard format string takes the form Axx, where A is an
// alphabetic character called the format specifier and xx is a
// sequence of digits called the precision specifier. The format
// specifier controls the type of formatting applied to the number and the
// precision specifier controls the number of significant digits or decimal
// places of the formatting operation. The following table describes the
// supported standard formats.
//
// C c - Currency format. The number is
// converted to a string that represents a currency amount. The conversion is
// controlled by the currency format information of the NumberFormatInfo
// used to format the number. The precision specifier indicates the desired
// number of decimal places. If the precision specifier is omitted, the default
// currency precision given by the NumberFormatInfo is used.
//
// D d - Decimal format. This format is
// supported for integral types only. The number is converted to a string of
// decimal digits, prefixed by a minus sign if the number is negative. The
// precision specifier indicates the minimum number of digits desired in the
// resulting string. If required, the number will be left-padded with zeros to
// produce the number of digits given by the precision specifier.
//
// E e Engineering (scientific) format.
// The number is converted to a string of the form
// "-d.ddd...E+ddd" or "-d.ddd...e+ddd", where each
// 'd' indicates a digit (0-9). The string starts with a minus sign if the
// number is negative, and one digit always precedes the decimal point. The
// precision specifier indicates the desired number of digits after the decimal
// point. If the precision specifier is omitted, a default of 6 digits after
// the decimal point is used. The format specifier indicates whether to prefix
// the exponent with an 'E' or an 'e'. The exponent is always consists of a
// plus or minus sign and three digits.
//
// F f Fixed point format. The number is
// converted to a string of the form "-ddd.ddd....", where each
// 'd' indicates a digit (0-9). The string starts with a minus sign if the
// number is negative. The precision specifier indicates the desired number of
// decimal places. If the precision specifier is omitted, the default numeric
// precision given by the NumberFormatInfo is used.
//
// G g - General format. The number is
// converted to the shortest possible decimal representation using fixed point
// or scientific format. The precision specifier determines the number of
// significant digits in the resulting string. If the precision specifier is
// omitted, the number of significant digits is determined by the type of the
// number being converted (10 for int, 19 for long, 7 for
// float, 15 for double, 19 for Currency, and 29 for
// Decimal). Trailing zeros after the decimal point are removed, and the
// resulting string contains a decimal point only if required. The resulting
// string uses fixed point format if the exponent of the number is less than
// the number of significant digits and greater than or equal to -4. Otherwise,
// the resulting string uses scientific format, and the case of the format
// specifier controls whether the exponent is prefixed with an 'E' or an 'e'.
//
// N n Number format. The number is
// converted to a string of the form "-d,ddd,ddd.ddd....", where
// each 'd' indicates a digit (0-9). The string starts with a minus sign if the
// number is negative. Thousand separators are inserted between each group of
// three digits to the left of the decimal point. The precision specifier
// indicates the desired number of decimal places. If the precision specifier
// is omitted, the default numeric precision given by the
// NumberFormatInfo is used.
//
// X x - Hexadecimal format. This format is
// supported for integral types only. The number is converted to a string of
// hexadecimal digits. The format specifier indicates whether to use upper or
// lower case characters for the hexadecimal digits above 9 ('X' for 'ABCDEF',
// and 'x' for 'abcdef'). The precision specifier indicates the minimum number
// of digits desired in the resulting string. If required, the number will be
// left-padded with zeros to produce the number of digits given by the
// precision specifier.
//
// Some examples of standard format strings and their results are shown in the
// table below. (The examples all assume a default NumberFormatInfo.)
//
// Value Format Result
// 12345.6789 C $12,345.68
// -12345.6789 C ($12,345.68)
// 12345 D 12345
// 12345 D8 00012345
// 12345.6789 E 1.234568E+004
// 12345.6789 E10 1.2345678900E+004
// 12345.6789 e4 1.2346e+004
// 12345.6789 F 12345.68
// 12345.6789 F0 12346
// 12345.6789 F6 12345.678900
// 12345.6789 G 12345.6789
// 12345.6789 G7 12345.68
// 123456789 G7 1.234568E8
// 12345.6789 N 12,345.68
// 123456789 N4 123,456,789.0000
// 0x2c45e x 2c45e
// 0x2c45e X 2C45E
// 0x2c45e X8 0002C45E
//
// Format strings that do not start with an alphabetic character, or that start
// with an alphabetic character followed by a non-digit, are called
// user-defined format strings. The following table describes the formatting
// characters that are supported in user defined format strings.
//
//
// 0 - Digit placeholder. If the value being
// formatted has a digit in the position where the '0' appears in the format
// string, then that digit is copied to the output string. Otherwise, a '0' is
// stored in that position in the output string. The position of the leftmost
// '0' before the decimal point and the rightmost '0' after the decimal point
// determines the range of digits that are always present in the output
// string.
//
// # - Digit placeholder. If the value being
// formatted has a digit in the position where the '#' appears in the format
// string, then that digit is copied to the output string. Otherwise, nothing
// is stored in that position in the output string.
//
// . - Decimal point. The first '.' character
// in the format string determines the location of the decimal separator in the
// formatted value; any additional '.' characters are ignored. The actual
// character used as a the decimal separator in the output string is given by
// the NumberFormatInfo used to format the number.
//
// , - Thousand separator and number scaling.
// The ',' character serves two purposes. First, if the format string contains
// a ',' character between two digit placeholders (0 or #) and to the left of
// the decimal point if one is present, then the output will have thousand
// separators inserted between each group of three digits to the left of the
// decimal separator. The actual character used as a the decimal separator in
// the output string is given by the NumberFormatInfo used to format the
// number. Second, if the format string contains one or more ',' characters
// immediately to the left of the decimal point, or after the last digit
// placeholder if there is no decimal point, then the number will be divided by
// 1000 times the number of ',' characters before it is formatted. For example,
// the format string '0,,' will represent 100 million as just 100. Use of the
// ',' character to indicate scaling does not also cause the formatted number
// to have thousand separators. Thus, to scale a number by 1 million and insert
// thousand separators you would use the format string '#,##0,,'.
//
// % - Percentage placeholder. The presence of
// a '%' character in the format string causes the number to be multiplied by
// 100 before it is formatted. The '%' character itself is inserted in the
// output string where it appears in the format string.
//
// E+ E- e+ e- - Scientific notation.
// If any of the strings 'E+', 'E-', 'e+', or 'e-' are present in the format
// string and are immediately followed by at least one '0' character, then the
// number is formatted using scientific notation with an 'E' or 'e' inserted
// between the number and the exponent. The number of '0' characters following
// the scientific notation indicator determines the minimum number of digits to
// output for the exponent. The 'E+' and 'e+' formats indicate that a sign
// character (plus or minus) should always precede the exponent. The 'E-' and
// 'e-' formats indicate that a sign character should only precede negative
// exponents.
//
// \ - Literal character. A backslash character
// causes the next character in the format string to be copied to the output
// string as-is. The backslash itself isn't copied, so to place a backslash
// character in the output string, use two backslashes (\\) in the format
// string.
//
// 'ABC' "ABC" - Literal string. Characters
// enclosed in single or double quotation marks are copied to the output string
// as-is and do not affect formatting.
//
// ; - Section separator. The ';' character is
// used to separate sections for positive, negative, and zero numbers in the
// format string.
//
// Other - All other characters are copied to
// the output string in the position they appear.
//
// For fixed point formats (formats not containing an 'E+', 'E-', 'e+', or
// 'e-'), the number is rounded to as many decimal places as there are digit
// placeholders to the right of the decimal point. If the format string does
// not contain a decimal point, the number is rounded to the nearest
// integer. If the number has more digits than there are digit placeholders to
// the left of the decimal point, the extra digits are copied to the output
// string immediately before the first digit placeholder.
//
// For scientific formats, the number is rounded to as many significant digits
// as there are digit placeholders in the format string.
//
// To allow for different formatting of positive, negative, and zero values, a
// user-defined format string may contain up to three sections separated by
// semicolons. The results of having one, two, or three sections in the format
// string are described in the table below.
//
// Sections:
//
// One - The format string applies to all values.
//
// Two - The first section applies to positive values
// and zeros, and the second section applies to negative values. If the number
// to be formatted is negative, but becomes zero after rounding according to
// the format in the second section, then the resulting zero is formatted
// according to the first section.
//
// Three - The first section applies to positive
// values, the second section applies to negative values, and the third section
// applies to zeros. The second section may be left empty (by having no
// characters between the semicolons), in which case the first section applies
// to all non-zero values. If the number to be formatted is non-zero, but
// becomes zero after rounding according to the format in the first or second
// section, then the resulting zero is formatted according to the third
// section.
//
// For both standard and user-defined formatting operations on values of type
// float and double, if the value being formatted is a NaN (Not
// a Number) or a positive or negative infinity, then regardless of the format
// string, the resulting string is given by the NaNSymbol,
// PositiveInfinitySymbol, or NegativeInfinitySymbol property of
// the NumberFormatInfo used to format the number.
internal static partial class Number
{
internal const int DecimalPrecision = 29; // Decimal.DecCalc also uses this value
// SinglePrecision and DoublePrecision represent the maximum number of digits required
// to guarantee that any given Single or Double can roundtrip. Some numbers may require
// less, but none will require more.
private const int SinglePrecision = 9;
private const int DoublePrecision = 17;
// SinglePrecisionCustomFormat and DoublePrecisionCustomFormat are used to ensure that
// custom format strings return the same string as in previous releases when the format
// would return x digits or less (where x is the value of the corresponding constant).
// In order to support more digits, we would need to update ParseFormatSpecifier to pre-parse
// the format and determine exactly how many digits are being requested and whether they
// represent "significant digits" or "digits after the decimal point".
private const int SinglePrecisionCustomFormat = 7;
private const int DoublePrecisionCustomFormat = 15;
private const int DefaultPrecisionExponentialFormat = 6;
private const int MaxUInt32DecDigits = 10;
private const int CharStackBufferSize = 32;
private const string PosNumberFormat = "#";
private static readonly string[] s_singleDigitStringCache = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
private static readonly string[] s_posCurrencyFormats =
{
"$#", "#$", "$ #", "# $"
};
private static readonly string[] s_negCurrencyFormats =
{
"($#)", "-$#", "$-#", "$#-",
"(#$)", "-#$", "#-$", "#$-",
"-# $", "-$ #", "# $-", "$ #-",
"$ -#", "#- $", "($ #)", "(# $)"
};
private static readonly string[] s_posPercentFormats =
{
"# %", "#%", "%#", "% #"
};
private static readonly string[] s_negPercentFormats =
{
"-# %", "-#%", "-%#",
"%-#", "%#-",
"#-%", "#%-",
"-% #", "# %-", "% #-",
"% -#", "#- %"
};
private static readonly string[] s_negNumberFormats =
{
"(#)", "-#", "- #", "#-", "# -",
};
public static unsafe string FormatDecimal(decimal value, ReadOnlySpan<char> format, NumberFormatInfo info)
{
char fmt = ParseFormatSpecifier(format, out int digits);
byte* pDigits = stackalloc byte[DecimalNumberBufferLength];
NumberBuffer number = new NumberBuffer(NumberBufferKind.Decimal, pDigits, DecimalNumberBufferLength);
DecimalToNumber(ref value, ref number);
char* stackPtr = stackalloc char[CharStackBufferSize];
ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
if (fmt != 0)
{
NumberToString(ref sb, ref number, fmt, digits, info);
}
else
{
NumberToStringFormat(ref sb, ref number, format, info);
}
return sb.ToString();
}
public static unsafe bool TryFormatDecimal(decimal value, ReadOnlySpan<char> format, NumberFormatInfo info, Span<char> destination, out int charsWritten)
{
char fmt = ParseFormatSpecifier(format, out int digits);
byte* pDigits = stackalloc byte[DecimalNumberBufferLength];
NumberBuffer number = new NumberBuffer(NumberBufferKind.Decimal, pDigits, DecimalNumberBufferLength);
DecimalToNumber(ref value, ref number);
char* stackPtr = stackalloc char[CharStackBufferSize];
ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
if (fmt != 0)
{
NumberToString(ref sb, ref number, fmt, digits, info);
}
else
{
NumberToStringFormat(ref sb, ref number, format, info);
}
return sb.TryCopyTo(destination, out charsWritten);
}
internal static unsafe void DecimalToNumber(ref decimal d, ref NumberBuffer number)
{
byte* buffer = number.GetDigitsPointer();
number.DigitsCount = DecimalPrecision;
number.IsNegative = d.IsNegative;
byte* p = buffer + DecimalPrecision;
while ((d.Mid | d.High) != 0)
{
p = UInt32ToDecChars(p, decimal.DecDivMod1E9(ref d), 9);
}
p = UInt32ToDecChars(p, d.Low, 0);
int i = (int)((buffer + DecimalPrecision) - p);
number.DigitsCount = i;
number.Scale = i - d.Scale;
byte* dst = number.GetDigitsPointer();
while (--i >= 0)
{
*dst++ = *p++;
}
*dst = (byte)('\0');
number.CheckConsistency();
}
public static string FormatDouble(double value, string? format, NumberFormatInfo info)
{
Span<char> stackBuffer = stackalloc char[CharStackBufferSize];
var sb = new ValueStringBuilder(stackBuffer);
return FormatDouble(ref sb, value, format, info) ?? sb.ToString();
}
public static bool TryFormatDouble(double value, ReadOnlySpan<char> format, NumberFormatInfo info, Span<char> destination, out int charsWritten)
{
Span<char> stackBuffer = stackalloc char[CharStackBufferSize];
var sb = new ValueStringBuilder(stackBuffer);
string? s = FormatDouble(ref sb, value, format, info);
return s != null ?
TryCopyTo(s, destination, out charsWritten) :
sb.TryCopyTo(destination, out charsWritten);
}
private static int GetFloatingPointMaxDigitsAndPrecision(char fmt, ref int precision, NumberFormatInfo info, out bool isSignificantDigits)
{
if (fmt == 0)
{
isSignificantDigits = true;
return precision;
}
int maxDigits = precision;
switch (fmt)
{
case 'C':
case 'c':
{
// The currency format uses the precision specifier to indicate the number of
// decimal digits to format. This defaults to NumberFormatInfo.CurrencyDecimalDigits.
if (precision == -1)
{
precision = info.CurrencyDecimalDigits;
}
isSignificantDigits = false;
break;
}
case 'E':
case 'e':
{
// The exponential format uses the precision specifier to indicate the number of
// decimal digits to format. This defaults to 6. However, the exponential format
// also always formats a single integral digit, so we need to increase the precision
// specifier and treat it as the number of significant digits to account for this.
if (precision == -1)
{
precision = DefaultPrecisionExponentialFormat;
}
precision++;
isSignificantDigits = true;
break;
}
case 'F':
case 'f':
case 'N':
case 'n':
{
// The fixed-point and number formats use the precision specifier to indicate the number
// of decimal digits to format. This defaults to NumberFormatInfo.NumberDecimalDigits.
if (precision == -1)
{
precision = info.NumberDecimalDigits;
}
isSignificantDigits = false;
break;
}
case 'G':
case 'g':
{
// The general format uses the precision specifier to indicate the number of significant
// digits to format. This defaults to the shortest roundtrippable string. Additionally,
// given that we can't return zero significant digits, we treat 0 as returning the shortest
// roundtrippable string as well.
if (precision == 0)
{
precision = -1;
}
isSignificantDigits = true;
break;
}
case 'P':
case 'p':
{
// The percent format uses the precision specifier to indicate the number of
// decimal digits to format. This defaults to NumberFormatInfo.PercentDecimalDigits.
// However, the percent format also always multiplies the number by 100, so we need
// to increase the precision specifier to ensure we get the appropriate number of digits.
if (precision == -1)
{
precision = info.PercentDecimalDigits;
}
precision += 2;
isSignificantDigits = false;
break;
}
case 'R':
case 'r':
{
// The roundtrip format ignores the precision specifier and always returns the shortest
// roundtrippable string.
precision = -1;
isSignificantDigits = true;
break;
}
default:
{
throw new FormatException(SR.Argument_BadFormatSpecifier);
}
}
return maxDigits;
}
/// <summary>Formats the specified value according to the specified format and info.</summary>
/// <returns>
/// Non-null if an existing string can be returned, in which case the builder will be unmodified.
/// Null if no existing string was returned, in which case the formatted output is in the builder.
/// </returns>
private static unsafe string? FormatDouble(ref ValueStringBuilder sb, double value, ReadOnlySpan<char> format, NumberFormatInfo info)
{
if (!double.IsFinite(value))
{
if (double.IsNaN(value))
{
return info.NaNSymbol;
}
return double.IsNegative(value) ? info.NegativeInfinitySymbol : info.PositiveInfinitySymbol;
}
char fmt = ParseFormatSpecifier(format, out int precision);
byte* pDigits = stackalloc byte[DoubleNumberBufferLength];
if (fmt == '\0')
{
// For back-compat we currently specially treat the precision for custom
// format specifiers. The constant has more details as to why.
precision = DoublePrecisionCustomFormat;
}
NumberBuffer number = new NumberBuffer(NumberBufferKind.FloatingPoint, pDigits, DoubleNumberBufferLength);
number.IsNegative = double.IsNegative(value);
// We need to track the original precision requested since some formats
// accept values like 0 and others may require additional fixups.
int nMaxDigits = GetFloatingPointMaxDigitsAndPrecision(fmt, ref precision, info, out bool isSignificantDigits);
if ((value != 0.0) && (!isSignificantDigits || !Grisu3.TryRunDouble(value, precision, ref number)))
{
Dragon4Double(value, precision, isSignificantDigits, ref number);
}
number.CheckConsistency();
// When the number is known to be roundtrippable (either because we requested it be, or
// because we know we have enough digits to satisfy roundtrippability), we should validate
// that the number actually roundtrips back to the original result.
Debug.Assert(((precision != -1) && (precision < DoublePrecision)) || (BitConverter.DoubleToInt64Bits(value) == BitConverter.DoubleToInt64Bits(NumberToDouble(ref number))));
if (fmt != 0)
{
if (precision == -1)
{
Debug.Assert((fmt == 'G') || (fmt == 'g') || (fmt == 'R') || (fmt == 'r'));
// For the roundtrip and general format specifiers, when returning the shortest roundtrippable
// string, we need to update the maximum number of digits to be the greater of number.DigitsCount
// or DoublePrecision. This ensures that we continue returning "pretty" strings for values with
// less digits. One example this fixes is "-60", which would otherwise be formatted as "-6E+01"
// since DigitsCount would be 1 and the formatter would almost immediately switch to scientific notation.
nMaxDigits = Math.Max(number.DigitsCount, DoublePrecision);
}
NumberToString(ref sb, ref number, fmt, nMaxDigits, info);
}
else
{
Debug.Assert(precision == DoublePrecisionCustomFormat);
NumberToStringFormat(ref sb, ref number, format, info);
}
return null;
}
public static string FormatSingle(float value, string? format, NumberFormatInfo info)
{
Span<char> stackBuffer = stackalloc char[CharStackBufferSize];
var sb = new ValueStringBuilder(stackBuffer);
return FormatSingle(ref sb, value, format, info) ?? sb.ToString();
}
public static bool TryFormatSingle(float value, ReadOnlySpan<char> format, NumberFormatInfo info, Span<char> destination, out int charsWritten)
{
Span<char> stackBuffer = stackalloc char[CharStackBufferSize];
var sb = new ValueStringBuilder(stackBuffer);
string? s = FormatSingle(ref sb, value, format, info);
return s != null ?
TryCopyTo(s, destination, out charsWritten) :
sb.TryCopyTo(destination, out charsWritten);
}
/// <summary>Formats the specified value according to the specified format and info.</summary>
/// <returns>
/// Non-null if an existing string can be returned, in which case the builder will be unmodified.
/// Null if no existing string was returned, in which case the formatted output is in the builder.
/// </returns>
private static unsafe string? FormatSingle(ref ValueStringBuilder sb, float value, ReadOnlySpan<char> format, NumberFormatInfo info)
{
if (!float.IsFinite(value))
{
if (float.IsNaN(value))
{
return info.NaNSymbol;
}
return float.IsNegative(value) ? info.NegativeInfinitySymbol : info.PositiveInfinitySymbol;
}
char fmt = ParseFormatSpecifier(format, out int precision);
byte* pDigits = stackalloc byte[SingleNumberBufferLength];
if (fmt == '\0')
{
// For back-compat we currently specially treat the precision for custom
// format specifiers. The constant has more details as to why.
precision = SinglePrecisionCustomFormat;
}
NumberBuffer number = new NumberBuffer(NumberBufferKind.FloatingPoint, pDigits, SingleNumberBufferLength);
number.IsNegative = float.IsNegative(value);
// We need to track the original precision requested since some formats
// accept values like 0 and others may require additional fixups.
int nMaxDigits = GetFloatingPointMaxDigitsAndPrecision(fmt, ref precision, info, out bool isSignificantDigits);
if ((value != 0.0f) && (!isSignificantDigits || !Grisu3.TryRunSingle(value, precision, ref number)))
{
Dragon4Single(value, precision, isSignificantDigits, ref number);
}
number.CheckConsistency();
// When the number is known to be roundtrippable (either because we requested it be, or
// because we know we have enough digits to satisfy roundtrippability), we should validate
// that the number actually roundtrips back to the original result.
Debug.Assert(((precision != -1) && (precision < SinglePrecision)) || (BitConverter.SingleToInt32Bits(value) == BitConverter.SingleToInt32Bits(NumberToSingle(ref number))));
if (fmt != 0)
{
if (precision == -1)
{
Debug.Assert((fmt == 'G') || (fmt == 'g') || (fmt == 'R') || (fmt == 'r'));
// For the roundtrip and general format specifiers, when returning the shortest roundtrippable
// string, we need to update the maximum number of digits to be the greater of number.DigitsCount
// or SinglePrecision. This ensures that we continue returning "pretty" strings for values with
// less digits. One example this fixes is "-60", which would otherwise be formatted as "-6E+01"
// since DigitsCount would be 1 and the formatter would almost immediately switch to scientific notation.
nMaxDigits = Math.Max(number.DigitsCount, SinglePrecision);
}
NumberToString(ref sb, ref number, fmt, nMaxDigits, info);
}
else
{
Debug.Assert(precision == SinglePrecisionCustomFormat);
NumberToStringFormat(ref sb, ref number, format, info);
}
return null;
}
private static bool TryCopyTo(string source, Span<char> destination, out int charsWritten)
{
Debug.Assert(source != null);
if (source.AsSpan().TryCopyTo(destination))
{
charsWritten = source.Length;
return true;
}
charsWritten = 0;
return false;
}
public static unsafe string FormatInt32(int value, ReadOnlySpan<char> format, IFormatProvider? provider)
{
// Fast path for default format with a non-negative value
if (value >= 0 && format.Length == 0)
{
return UInt32ToDecStr((uint)value, digits: -1);
}
char fmt = ParseFormatSpecifier(format, out int digits);
char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
{
return value >= 0 ?
UInt32ToDecStr((uint)value, digits) :
NegativeInt32ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign);
}
else if (fmtUpper == 'X')
{
// The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
// hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code produces lowercase.
return Int32ToHexStr(value, (char)(fmt - ('X' - 'A' + 10)), digits);
}
else
{
NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
byte* pDigits = stackalloc byte[Int32NumberBufferLength];
NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, Int32NumberBufferLength);
Int32ToNumber(value, ref number);
char* stackPtr = stackalloc char[CharStackBufferSize];
ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
if (fmt != 0)
{
NumberToString(ref sb, ref number, fmt, digits, info);
}
else
{
NumberToStringFormat(ref sb, ref number, format, info);
}
return sb.ToString();
}
}
public static unsafe bool TryFormatInt32(int value, ReadOnlySpan<char> format, IFormatProvider? provider, Span<char> destination, out int charsWritten)
{
// Fast path for default format with a non-negative value
if (value >= 0 && format.Length == 0)
{
return TryUInt32ToDecStr((uint)value, digits: -1, destination, out charsWritten);
}
char fmt = ParseFormatSpecifier(format, out int digits);
char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
{
return value >= 0 ?
TryUInt32ToDecStr((uint)value, digits, destination, out charsWritten) :
TryNegativeInt32ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign, destination, out charsWritten);
}
else if (fmtUpper == 'X')
{
// The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
// hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code produces lowercase.
return TryInt32ToHexStr(value, (char)(fmt - ('X' - 'A' + 10)), digits, destination, out charsWritten);
}
else
{
NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
byte* pDigits = stackalloc byte[Int32NumberBufferLength];
NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, Int32NumberBufferLength);
Int32ToNumber(value, ref number);
char* stackPtr = stackalloc char[CharStackBufferSize];
ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
if (fmt != 0)
{
NumberToString(ref sb, ref number, fmt, digits, info);
}
else
{
NumberToStringFormat(ref sb, ref number, format, info);
}
return sb.TryCopyTo(destination, out charsWritten);
}
}
public static unsafe string FormatUInt32(uint value, ReadOnlySpan<char> format, IFormatProvider? provider)
{
// Fast path for default format
if (format.Length == 0)
{
return UInt32ToDecStr(value, digits: -1);
}
char fmt = ParseFormatSpecifier(format, out int digits);
char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
{
return UInt32ToDecStr(value, digits);
}
else if (fmtUpper == 'X')
{
// The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
// hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code produces lowercase.
return Int32ToHexStr((int)value, (char)(fmt - ('X' - 'A' + 10)), digits);
}
else
{
NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
byte* pDigits = stackalloc byte[UInt32NumberBufferLength];
NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, UInt32NumberBufferLength);
UInt32ToNumber(value, ref number);
char* stackPtr = stackalloc char[CharStackBufferSize];
ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
if (fmt != 0)
{
NumberToString(ref sb, ref number, fmt, digits, info);
}
else
{
NumberToStringFormat(ref sb, ref number, format, info);
}
return sb.ToString();
}
}
public static unsafe bool TryFormatUInt32(uint value, ReadOnlySpan<char> format, IFormatProvider? provider, Span<char> destination, out int charsWritten)
{
// Fast path for default format
if (format.Length == 0)
{
return TryUInt32ToDecStr(value, digits: -1, destination, out charsWritten);
}
char fmt = ParseFormatSpecifier(format, out int digits);
char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
{
return TryUInt32ToDecStr(value, digits, destination, out charsWritten);
}
else if (fmtUpper == 'X')
{
// The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
// hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code produces lowercase.
return TryInt32ToHexStr((int)value, (char)(fmt - ('X' - 'A' + 10)), digits, destination, out charsWritten);
}
else
{
NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
byte* pDigits = stackalloc byte[UInt32NumberBufferLength];
NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, UInt32NumberBufferLength);
UInt32ToNumber(value, ref number);
char* stackPtr = stackalloc char[CharStackBufferSize];
ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
if (fmt != 0)
{
NumberToString(ref sb, ref number, fmt, digits, info);
}
else
{
NumberToStringFormat(ref sb, ref number, format, info);
}
return sb.TryCopyTo(destination, out charsWritten);
}
}
public static unsafe string FormatInt64(long value, ReadOnlySpan<char> format, IFormatProvider? provider)
{
// Fast path for default format with a non-negative value
if (value >= 0 && format.Length == 0)
{
return UInt64ToDecStr((ulong)value, digits: -1);
}
char fmt = ParseFormatSpecifier(format, out int digits);
char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
{
return value >= 0 ?
UInt64ToDecStr((ulong)value, digits) :
NegativeInt64ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign);
}
else if (fmtUpper == 'X')
{
// The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
// hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code
// produces lowercase.
return Int64ToHexStr(value, (char)(fmt - ('X' - 'A' + 10)), digits);
}
else
{
NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
byte* pDigits = stackalloc byte[Int64NumberBufferLength];
NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, Int64NumberBufferLength);
Int64ToNumber(value, ref number);
char* stackPtr = stackalloc char[CharStackBufferSize];
ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
if (fmt != 0)
{
NumberToString(ref sb, ref number, fmt, digits, info);
}
else
{
NumberToStringFormat(ref sb, ref number, format, info);
}
return sb.ToString();
}
}
public static unsafe bool TryFormatInt64(long value, ReadOnlySpan<char> format, IFormatProvider? provider, Span<char> destination, out int charsWritten)
{
// Fast path for default format with a non-negative value
if (value >= 0 && format.Length == 0)
{
return TryUInt64ToDecStr((ulong)value, digits: -1, destination, out charsWritten);
}
char fmt = ParseFormatSpecifier(format, out int digits);
char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
{
return value >= 0 ?
TryUInt64ToDecStr((ulong)value, digits, destination, out charsWritten) :
TryNegativeInt64ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign, destination, out charsWritten);
}
else if (fmtUpper == 'X')
{
// The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
// hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code
// produces lowercase.
return TryInt64ToHexStr(value, (char)(fmt - ('X' - 'A' + 10)), digits, destination, out charsWritten);
}
else
{
NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
byte* pDigits = stackalloc byte[Int64NumberBufferLength];
NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, Int64NumberBufferLength);
Int64ToNumber(value, ref number);
char* stackPtr = stackalloc char[CharStackBufferSize];
ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
if (fmt != 0)
{
NumberToString(ref sb, ref number, fmt, digits, info);
}
else
{
NumberToStringFormat(ref sb, ref number, format, info);
}
return sb.TryCopyTo(destination, out charsWritten);
}
}
public static unsafe string FormatUInt64(ulong value, ReadOnlySpan<char> format, IFormatProvider? provider)
{
// Fast path for default format
if (format.Length == 0)
{
return UInt64ToDecStr(value, digits: -1);
}
char fmt = ParseFormatSpecifier(format, out int digits);
char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
{
return UInt64ToDecStr(value, digits);
}
else if (fmtUpper == 'X')
{
// The fmt-(X-A+10) hack has the effect of dictating whether we produce uppercase or lowercase
// hex numbers for a-f. 'X' as the fmt code produces uppercase. 'x' as the format code
// produces lowercase.
return Int64ToHexStr((long)value, (char)(fmt - ('X' - 'A' + 10)), digits);
}
else
{
NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);
byte* pDigits = stackalloc byte[UInt64NumberBufferLength];
NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, pDigits, UInt64NumberBufferLength);
UInt64ToNumber(value, ref number);
char* stackPtr = stackalloc char[CharStackBufferSize];
ValueStringBuilder sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
if (fmt != 0)
{
NumberToString(ref sb, ref number, fmt, digits, info);
}
else
{