summaryrefslogtreecommitdiff
path: root/src/mscorlib/shared/System/Number.Formatting.cs
blob: 74395ab2f58ae7b90c2b413d53a749f704fb2316 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
// 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
        private const int FloatPrecision = 7;
        private const int DoublePrecision = 15;
        private const int ScaleNAN = unchecked((int)0x80000000);
        private const int ScaleINF = 0x7FFFFFFF;
        private const int MaxUInt32DecDigits = 10;
        private const int CharStackBufferSize = 32;
        private const string PosNumberFormat = "#";

        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 string FormatDecimal(decimal value, ReadOnlySpan<char> format, NumberFormatInfo info)
        {
            char fmt = ParseFormatSpecifier(format, out int digits);

            NumberBuffer number = default;
            DecimalToNumber(value, ref number);

            ValueStringBuilder sb;
            unsafe
            {
                char* stackPtr = stackalloc char[CharStackBufferSize];
                sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
            }

            if (fmt != 0)
            {
                NumberToString(ref sb, ref number, fmt, digits, info, isDecimal:true);
            }
            else
            {
                NumberToStringFormat(ref sb, ref number, format, info);
            }

            return sb.ToString();
        }

        public static bool TryFormatDecimal(decimal value, ReadOnlySpan<char> format, NumberFormatInfo info, Span<char> destination, out int charsWritten)
        {
            char fmt = ParseFormatSpecifier(format, out int digits);

            NumberBuffer number = default;
            DecimalToNumber(value, ref number);

            ValueStringBuilder sb;
            unsafe
            {
                char* stackPtr = stackalloc char[CharStackBufferSize];
                sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
            }

            if (fmt != 0)
            {
                NumberToString(ref sb, ref number, fmt, digits, info, isDecimal: true);
            }
            else
            {
                NumberToStringFormat(ref sb, ref number, format, info);
            }

            return sb.TryCopyTo(destination, out charsWritten);
        }

        private static unsafe void DecimalToNumber(decimal value, ref NumberBuffer number)
        {
            decimal d = value;

            char* buffer = number.digits;
            number.precision = DecimalPrecision;
            number.sign = d.IsNegative;

            char* 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.scale = i - d.Scale;

            char* dst = number.digits;
            while (--i >= 0)
            {
                *dst++ = *p++;
            }
            *dst = '\0';
        }

        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);
        }

        /// <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 string FormatDouble(ref ValueStringBuilder sb, double value, ReadOnlySpan<char> format, NumberFormatInfo info)
        {
            char fmt = ParseFormatSpecifier(format, out int digits);
            int precision = DoublePrecision;
            NumberBuffer number = default;

            switch (fmt)
            {
                case 'R':
                case 'r':
                    {
                        // In order to give numbers that are both friendly to display and round-trippable, we parse the
                        // number using 15 digits and then determine if it round trips to the same value. If it does, we
                        // convert that NUMBER to a string, otherwise we reparse using 17 digits and display that.
                        DoubleToNumber(value, DoublePrecision, ref number);
                        if (number.scale == ScaleNAN)
                        {
                            return info.NaNSymbol;
                        }
                        else if (number.scale == ScaleINF)
                        {
                            return number.sign ? info.NegativeInfinitySymbol : info.PositiveInfinitySymbol;
                        }

                        if (NumberToDouble(ref number) == value)
                        {
                            NumberToString(ref sb, ref number, 'G', DoublePrecision, info, isDecimal: false);
                        }
                        else
                        {
                            DoubleToNumber(value, 17, ref number);
                            NumberToString(ref sb, ref number, 'G', 17, info, isDecimal: false);
                        }

                        return null;
                    }

                case 'E':
                case 'e':
                    // Round values less than E14 to 15 digits
                    if (digits > 14)
                    {
                        precision = 17;
                    }
                    break;

                case 'G':
                case 'g':
                    // Round values less than G15 to 15 digits. G16 and G17 will not be touched.
                    if (digits > 15)
                    {
                        precision = 17;
                    }
                    break;
            }

            DoubleToNumber(value, precision, ref number);
            if (number.scale == ScaleNAN)
            {
                return info.NaNSymbol;
            }
            else if (number.scale == ScaleINF)
            {
                return number.sign ? info.NegativeInfinitySymbol : info.PositiveInfinitySymbol;
            }

            if (fmt != 0)
            {
                NumberToString(ref sb, ref number, fmt, digits, info, isDecimal: false);
            }
            else
            {
                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 string FormatSingle(ref ValueStringBuilder sb, float value, ReadOnlySpan<char> format, NumberFormatInfo info)
        {
            char fmt = ParseFormatSpecifier(format, out int digits);
            int precision = FloatPrecision;
            NumberBuffer number = default;

            switch (fmt)
            {
                case 'R':
                case 'r':
                    {
                        // In order to give numbers that are both friendly to display and round-trippable, we parse the
                        // number using 7 digits and then determine if it round trips to the same value. If it does, we
                        // convert that NUMBER to a string, otherwise we reparse using 9 digits and display that.
                        DoubleToNumber(value, FloatPrecision, ref number);
                        if (number.scale == ScaleNAN)
                        {
                            return info.NaNSymbol;
                        }
                        else if (number.scale == ScaleINF)
                        {
                            return number.sign ? info.NegativeInfinitySymbol : info.PositiveInfinitySymbol;
                        }

                        if ((float)NumberToDouble(ref number) == value)
                        {
                            NumberToString(ref sb, ref number, 'G', FloatPrecision, info, isDecimal: false);
                        }
                        else
                        {
                            DoubleToNumber(value, 9, ref number);
                            NumberToString(ref sb, ref number, 'G', 9, info, isDecimal: false);
                        }
                        return null;
                    }

                case 'E':
                case 'e':
                    // Round values less than E14 to 15 digits.
                    if (digits > 6)
                    {
                        precision = 9;
                    }
                    break;

                case 'G':
                case 'g':
                    // Round values less than G15 to 15 digits. G16 and G17 will not be touched.
                    if (digits > 7)
                    {
                        precision = 9;
                    }
                    break;
            }

            DoubleToNumber(value, precision, ref number);
            if (number.scale == ScaleNAN)
            {
                return info.NaNSymbol;
            }
            else if (number.scale == ScaleINF)
            {
                return number.sign ? info.NegativeInfinitySymbol : info.PositiveInfinitySymbol;
            }

            if (fmt != 0)
            {
                NumberToString(ref sb, ref number, fmt, digits, info, false);
            }
            else
            {
                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 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);
            NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);

            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, info.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
            {
                NumberBuffer number = default;
                Int32ToNumber(value, ref number);
                ValueStringBuilder sb;
                unsafe
                {
                    char* stackPtr = stackalloc char[CharStackBufferSize];
                    sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
                }
                if (fmt != 0)
                {
                    NumberToString(ref sb, ref number, fmt, digits, info, false);
                }
                else
                {
                    NumberToStringFormat(ref sb, ref number, format, info);
                }
                return sb.ToString();
            }
        }

        public static 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);
            NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);

            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, info.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
            {
                NumberBuffer number = default;
                Int32ToNumber(value, ref number);
                ValueStringBuilder sb;
                unsafe
                {
                    char* stackPtr = stackalloc char[CharStackBufferSize];
                    sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
                }
                if (fmt != 0)
                {
                    NumberToString(ref sb, ref number, fmt, digits, info, false);
                }
                else
                {
                    NumberToStringFormat(ref sb, ref number, format, info);
                }
                return sb.TryCopyTo(destination, out charsWritten);
            }
        }

        public static 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);
            NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);

            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
            {
                NumberBuffer number = default;
                UInt32ToNumber(value, ref number);
                ValueStringBuilder sb;
                unsafe
                {
                    char* stackPtr = stackalloc char[CharStackBufferSize];
                    sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
                }
                if (fmt != 0)
                {
                    NumberToString(ref sb, ref number, fmt, digits, info, false);
                }
                else
                {
                    NumberToStringFormat(ref sb, ref number, format, info);
                }
                return sb.ToString();
            }
        }

        public static 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);
            NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);

            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
            {
                NumberBuffer number = default;
                UInt32ToNumber(value, ref number);
                ValueStringBuilder sb;
                unsafe
                {
                    char* stackPtr = stackalloc char[CharStackBufferSize];
                    sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
                }
                if (fmt != 0)
                {
                    NumberToString(ref sb, ref number, fmt, digits, info, false);
                }
                else
                {
                    NumberToStringFormat(ref sb, ref number, format, info);
                }
                return sb.TryCopyTo(destination, out charsWritten);
            }
        }

        public static 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);
            NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);

            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, info.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
            {
                NumberBuffer number = default;
                Int64ToNumber(value, ref number);
                ValueStringBuilder sb;
                unsafe
                {
                    char* stackPtr = stackalloc char[CharStackBufferSize];
                    sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
                }
                if (fmt != 0)
                {
                    NumberToString(ref sb, ref number, fmt, digits, info, false);
                }
                else
                {
                    NumberToStringFormat(ref sb, ref number, format, info);
                }
                return sb.ToString();
            }
        }

        public static 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);
            NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);

            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, info.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
            {
                NumberBuffer number = default;
                Int64ToNumber(value, ref number);
                ValueStringBuilder sb;
                unsafe
                {
                    char* stackPtr = stackalloc char[CharStackBufferSize];
                    sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
                }
                if (fmt != 0)
                {
                    NumberToString(ref sb, ref number, fmt, digits, info, false);
                }
                else
                {
                    NumberToStringFormat(ref sb, ref number, format, info);
                }
                return sb.TryCopyTo(destination, out charsWritten);
            }
        }

        public static 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);
            NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);

            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
            {
                NumberBuffer number = default;
                UInt64ToNumber(value, ref number);
                ValueStringBuilder sb;
                unsafe
                {
                    char* stackPtr = stackalloc char[CharStackBufferSize];
                    sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
                }
                if (fmt != 0)
                {
                    NumberToString(ref sb, ref number, fmt, digits, info, false);
                }
                else
                {
                    NumberToStringFormat(ref sb, ref number, format, info);
                }
                return sb.ToString();
            }
        }

        public static bool TryFormatUInt64(ulong value, ReadOnlySpan<char> format, IFormatProvider provider, Span<char> destination, out int charsWritten)
        {
            // Fast path for default format
            if (format.Length == 0)
            {
                return TryUInt64ToDecStr(value, digits: -1, destination, out charsWritten);
            }

            char fmt = ParseFormatSpecifier(format, out int digits);
            NumberFormatInfo info = NumberFormatInfo.GetInstance(provider);

            char fmtUpper = (char)(fmt & 0xFFDF); // ensure fmt is upper-cased for purposes of comparison
            if ((fmtUpper == 'G' && digits < 1) || fmtUpper == 'D')
            {
                return TryUInt64ToDecStr(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 TryInt64ToHexStr((long)value, (char)(fmt - ('X' - 'A' + 10)), digits, destination, out charsWritten);
            }
            else
            {
                NumberBuffer number = default;
                UInt64ToNumber(value, ref number);
                ValueStringBuilder sb;
                unsafe
                {
                    char* stackPtr = stackalloc char[CharStackBufferSize];
                    sb = new ValueStringBuilder(new Span<char>(stackPtr, CharStackBufferSize));
                }
                if (fmt != 0)
                {
                    NumberToString(ref sb, ref number, fmt, digits, info, false);
                }
                else
                {
                    NumberToStringFormat(ref sb, ref number, format, info);
                }
                return sb.TryCopyTo(destination, out charsWritten);
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)] // called from only one location
        private static unsafe void Int32ToNumber(int value, ref NumberBuffer number)
        {
            number.precision = Int32Precision;

            if (value >= 0)
            {
                number.sign = false;
            }
            else
            {
                number.sign = true;
                value = -value;
            }

            char* buffer = number.digits;
            char* p = UInt32ToDecChars(buffer + Int32Precision, (uint)value, 0);
            int i = (int)(buffer + Int32Precision - p);

            number.scale = i;

            char* dst = number.digits;
            while (--i >= 0)
                *dst++ = *p++;
            *dst = '\0';
        }

        private static unsafe string NegativeInt32ToDecStr(int value, int digits, string sNegative)
        {
            Debug.Assert(value < 0);

            if (digits < 1)
                digits = 1;

            int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits((uint)(-value))) + sNegative.Length;
            string result = string.FastAllocateString(bufferLength);
            fixed (char* buffer = result)
            {
                char* p = UInt32ToDecChars(buffer + bufferLength, (uint)(-value), digits);
                Debug.Assert(p == buffer + sNegative.Length);

                for (int i = sNegative.Length - 1; i >= 0; i--)
                {
                    *(--p) = sNegative[i];
                }
                Debug.Assert(p == buffer);
            }
            return result;
        }

        private static unsafe bool TryNegativeInt32ToDecStr(int value, int digits, string sNegative, Span<char> destination, out int charsWritten)
        {
            Debug.Assert(value < 0);

            if (digits < 1)
                digits = 1;

            int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits((uint)(-value))) + sNegative.Length;
            if (bufferLength > destination.Length)
            {
                charsWritten = 0;
                return false;
            }

            charsWritten = bufferLength;
            fixed (char* buffer = &MemoryMarshal.GetReference(destination))
            {
                char* p = UInt32ToDecChars(buffer + bufferLength, (uint)(-value), digits);
                Debug.Assert(p == buffer + sNegative.Length);

                for (int i = sNegative.Length - 1; i >= 0; i--)
                {
                    *(--p) = sNegative[i];
                }
                Debug.Assert(p == buffer);
            }
            return true;
        }

        private static unsafe string Int32ToHexStr(int value, char hexBase, int digits)
        {
            if (digits < 1)
                digits = 1;

            int bufferLength = Math.Max(digits, FormattingHelpers.CountHexDigits((uint)value));
            string result = string.FastAllocateString(bufferLength);
            fixed (char* buffer = result)
            {
                char* p = Int32ToHexChars(buffer + bufferLength, (uint)value, hexBase, digits);
                Debug.Assert(p == buffer);
            }
            return result;
        }

        private static unsafe bool TryInt32ToHexStr(int value, char hexBase, int digits, Span<char> destination, out int charsWritten)
        {
            if (digits < 1)
                digits = 1;

            int bufferLength = Math.Max(digits, FormattingHelpers.CountHexDigits((uint)value));
            if (bufferLength > destination.Length)
            {
                charsWritten = 0;
                return false;
            }

            charsWritten = bufferLength;
            fixed (char* buffer = &MemoryMarshal.GetReference(destination))
            {
                char* p = Int32ToHexChars(buffer + bufferLength, (uint)value, hexBase, digits);
                Debug.Assert(p == buffer);
            }
            return true;
        }

        private static unsafe char* Int32ToHexChars(char* buffer, uint value, int hexBase, int digits)
        {
            while (--digits >= 0 || value != 0)
            {
                byte digit = (byte)(value & 0xF);
                *(--buffer) = (char)(digit + (digit < 10 ? (byte)'0' : hexBase));
                value >>= 4;
            }
            return buffer;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)] // called from only one location
        private static unsafe void UInt32ToNumber(uint value, ref NumberBuffer number)
        {
            number.precision = UInt32Precision;
            number.sign = false;

            char* buffer = number.digits;
            char* p = UInt32ToDecChars(buffer + UInt32Precision, value, 0);
            int i = (int)(buffer + UInt32Precision - p);
            number.scale = i;

            char* dst = number.digits;
            while (--i >= 0)
                *dst++ = *p++;
            *dst = '\0';
        }

        internal static unsafe char* UInt32ToDecChars(char* bufferEnd, uint value, int digits)
        {
            while (--digits >= 0 || value != 0)
            {
                // TODO https://github.com/dotnet/coreclr/issues/3439
                uint newValue = value / 10;
                *(--bufferEnd) = (char)(value - (newValue * 10) + '0');
                value = newValue;
            }
            return bufferEnd;
        }

        private static unsafe string UInt32ToDecStr(uint value, int digits)
        {
            int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value));
            string result = string.FastAllocateString(bufferLength);
            fixed (char* buffer = result)
            {
                char* p = buffer + bufferLength;
                if (digits <= 1)
                {
                    do
                    {
                        // TODO https://github.com/dotnet/coreclr/issues/3439
                        uint div = value / 10;
                        *(--p) = (char)('0' + value - (div * 10));
                        value = div;
                    }
                    while (value != 0);
                }
                else
                {
                    p = UInt32ToDecChars(p, value, digits);
                }
                Debug.Assert(p == buffer);
            }
            return result;
        }

        private static unsafe bool TryUInt32ToDecStr(uint value, int digits, Span<char> destination, out int charsWritten)
        {
            int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value));
            if (bufferLength > destination.Length)
            {
                charsWritten = 0;
                return false;
            }

            charsWritten = bufferLength;
            fixed (char* buffer = &MemoryMarshal.GetReference(destination))
            {
                char* p = buffer + bufferLength;
                if (digits <= 1)
                {
                    do
                    {
                        // TODO https://github.com/dotnet/coreclr/issues/3439
                        uint div = value / 10;
                        *(--p) = (char)('0' + value - (div * 10));
                        value = div;
                    }
                    while (value != 0);
                }
                else
                {
                    p = UInt32ToDecChars(p, value, digits);
                }
                Debug.Assert(p == buffer);
            }
            return true;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static unsafe bool TryCopyTo(char* src, int length, Span<char> destination, out int charsWritten)
        {
            if (new ReadOnlySpan<char>(src, length).TryCopyTo(destination))
            {
                charsWritten = length;
                return true;
            }
            else
            {
                charsWritten = 0;
                return false;
            }
        }

        private static unsafe void Int64ToNumber(long input, ref NumberBuffer number)
        {
            ulong value = (ulong)input;
            number.sign = input < 0;
            number.precision = Int64Precision;
            if (number.sign)
            {
                value = (ulong)(-input);
            }

            char* buffer = number.digits;
            char* p = buffer + Int64Precision;
            while (High32(value) != 0)
                p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9);
            p = UInt32ToDecChars(p, Low32(value), 0);
            int i = (int)(buffer + Int64Precision - p);

            number.scale = i;

            char* dst = number.digits;
            while (--i >= 0)
                *dst++ = *p++;
            *dst = '\0';
        }

        private static unsafe string NegativeInt64ToDecStr(long input, int digits, string sNegative)
        {
            Debug.Assert(input < 0);

            if (digits < 1)
            {
                digits = 1;
            }

            ulong value = (ulong)(-input);

            int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value)) + sNegative.Length;
            string result = string.FastAllocateString(bufferLength);
            fixed (char* buffer = result)
            {
                char* p = buffer + bufferLength;
                while (High32(value) != 0)
                {
                    p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9);
                    digits -= 9;
                }
                p = UInt32ToDecChars(p, Low32(value), digits);
                Debug.Assert(p == buffer + sNegative.Length);

                for (int i = sNegative.Length - 1; i >= 0; i--)
                {
                    *(--p) = sNegative[i];
                }
                Debug.Assert(p == buffer);
            }
            return result;
        }

        private static unsafe bool TryNegativeInt64ToDecStr(long input, int digits, string sNegative, Span<char> destination, out int charsWritten)
        {
            Debug.Assert(input < 0);

            if (digits < 1)
            {
                digits = 1;
            }

            ulong value = (ulong)(-input);

            int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits((ulong)(-input))) + sNegative.Length;
            if (bufferLength > destination.Length)
            {
                charsWritten = 0;
                return false;
            }

            charsWritten = bufferLength;
            fixed (char* buffer = &MemoryMarshal.GetReference(destination))
            {
                char* p = buffer + bufferLength;
                while (High32(value) != 0)
                {
                    p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9);
                    digits -= 9;
                }
                p = UInt32ToDecChars(p, Low32(value), digits);
                Debug.Assert(p == buffer + sNegative.Length);

                for (int i = sNegative.Length - 1; i >= 0; i--)
                {
                    *(--p) = sNegative[i];
                }
                Debug.Assert(p == buffer);
            }
            return true;
        }

        private static unsafe string Int64ToHexStr(long value, char hexBase, int digits)
        {
            int bufferLength = Math.Max(digits, FormattingHelpers.CountHexDigits((ulong)value));
            string result = string.FastAllocateString(bufferLength);
            fixed (char* buffer = result)
            {
                char* p = buffer + bufferLength;
                if (High32((ulong)value) != 0)
                {
                    p = Int32ToHexChars(p, Low32((ulong)value), hexBase, 8);
                    p = Int32ToHexChars(p, High32((ulong)value), hexBase, digits - 8);
                }
                else
                {
                    p = Int32ToHexChars(p, Low32((ulong)value), hexBase, Math.Max(digits, 1));
                }
                Debug.Assert(p == buffer);
            }
            return result;
        }

        private static unsafe bool TryInt64ToHexStr(long value, char hexBase, int digits, Span<char> destination, out int charsWritten)
        {
            int bufferLength = Math.Max(digits, FormattingHelpers.CountHexDigits((ulong)value));
            if (bufferLength > destination.Length)
            {
                charsWritten = 0;
                return false;
            }

            charsWritten = bufferLength;
            fixed (char* buffer = &MemoryMarshal.GetReference(destination))
            {
                char* p = buffer + bufferLength;
                if (High32((ulong)value) != 0)
                {
                    p = Int32ToHexChars(p, Low32((ulong)value), hexBase, 8);
                    p = Int32ToHexChars(p, High32((ulong)value), hexBase, digits - 8);
                }
                else
                {
                    p = Int32ToHexChars(p, Low32((ulong)value), hexBase, Math.Max(digits, 1));
                }
                Debug.Assert(p == buffer);
            }
            return true;
        }

        private static unsafe void UInt64ToNumber(ulong value, ref NumberBuffer number)
        {
            number.precision = UInt64Precision;
            number.sign = false;

            char* buffer = number.digits;
            char* p = buffer + UInt64Precision;

            while (High32(value) != 0)
                p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9);
            p = UInt32ToDecChars(p, Low32(value), 0);
            int i = (int)(buffer + UInt64Precision - p);

            number.scale = i;

            char* dst = number.digits;
            while (--i >= 0)
                *dst++ = *p++;
            *dst = '\0';
        }

        private static unsafe string UInt64ToDecStr(ulong value, int digits)
        {
            if (digits < 1)
                digits = 1;

            int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value));
            string result = string.FastAllocateString(bufferLength);
            fixed (char* buffer = result)
            {
                char* p = buffer + bufferLength;
                while (High32(value) != 0)
                {
                    p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9);
                    digits -= 9;
                }
                p = UInt32ToDecChars(p, Low32(value), digits);
                Debug.Assert(p == buffer);
            }
            return result;
        }

        private static unsafe bool TryUInt64ToDecStr(ulong value, int digits, Span<char> destination, out int charsWritten)
        {
            if (digits < 1)
                digits = 1;

            int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value));
            if (bufferLength > destination.Length)
            {
                charsWritten = 0;
                return false;
            }

            charsWritten = bufferLength;
            fixed (char* buffer = &MemoryMarshal.GetReference(destination))
            {
                char* p = buffer + bufferLength;
                while (High32(value) != 0)
                {
                    p = UInt32ToDecChars(p, Int64DivMod1E9(ref value), 9);
                    digits -= 9;
                }
                p = UInt32ToDecChars(p, Low32(value), digits);
                Debug.Assert(p == buffer);
            }
            return true;
        }

        internal static unsafe char ParseFormatSpecifier(ReadOnlySpan<char> format, out int digits)
        {
            char c = default;
            if (format.Length > 0)
            {
                // If the format begins with a symbol, see if it's a standard format
                // with or without a specified number of digits.
                c = format[0];
                if ((uint)(c - 'A') <= 'Z' - 'A' ||
                    (uint)(c - 'a') <= 'z' - 'a')
                {
                    // Fast path for sole symbol, e.g. "D"
                    if (format.Length == 1)
                    {
                        digits = -1;
                        return c;
                    }

                    if (format.Length == 2)
                    {
                        // Fast path for symbol and single digit, e.g. "X4"
                        int d = format[1] - '0';
                        if ((uint)d < 10)
                        {
                            digits = d;
                            return c;
                        }
                    }
                    else if (format.Length == 3)
                    {
                        // Fast path for symbol and double digit, e.g. "F12"
                        int d1 = format[1] - '0', d2 = format[2] - '0';
                        if ((uint)d1 < 10 && (uint)d2 < 10)
                        {
                            digits = d1 * 10 + d2;
                            return c;
                        }
                    }

                    // Fallback for symbol and any length digits.  The digits value must be >= 0 && <= 99,
                    // but it can begin with any number of 0s, and thus we may need to check more than two
                    // digits.  Further, for compat, we need to stop when we hit a null char.
                    int n = 0;
                    int i = 1;
                    while (i < format.Length && (((uint)format[i] - '0') < 10) && n < 10)
                    {
                        n = (n * 10) + format[i++] - '0';
                    }

                    // If we're at the end of the digits rather than having stopped because we hit something
                    // other than a digit or overflowed, return the standard format info.
                    if (i == format.Length || format[i] == '\0')
                    {
                        digits = n;
                        return c;
                    }
                }
            }

            // Default empty format to be "G"; custom format is signified with '\0'.
            digits = -1;
            return format.Length == 0 || c == '\0' ? // For compat, treat '\0' as the end of the specifier, even if the specifier extends beyond it.
                'G' : 
                '\0';
        }

        internal static unsafe void NumberToString(ref ValueStringBuilder sb, ref NumberBuffer number, char format, int nMaxDigits, NumberFormatInfo info, bool isDecimal)
        {
            int nMinDigits = -1;

            switch (format)
            {
                case 'C':
                case 'c':
                    {
                        nMinDigits = nMaxDigits >= 0 ? nMaxDigits : info.CurrencyDecimalDigits;
                        if (nMaxDigits < 0)
                            nMaxDigits = info.CurrencyDecimalDigits;

                        RoundNumber(ref number, number.scale + nMaxDigits); // Don't change this line to use digPos since digCount could have its sign changed.

                        FormatCurrency(ref sb, ref number, nMinDigits, nMaxDigits, info);

                        break;
                    }

                case 'F':
                case 'f':
                    {
                        if (nMaxDigits < 0)
                            nMaxDigits = nMinDigits = info.NumberDecimalDigits;
                        else
                            nMinDigits = nMaxDigits;

                        RoundNumber(ref number, number.scale + nMaxDigits);

                        if (number.sign)
                            sb.Append(info.NegativeSign);

                        FormatFixed(ref sb, ref number, nMinDigits, nMaxDigits, info, null, info.NumberDecimalSeparator, null);

                        break;
                    }

                case 'N':
                case 'n':
                    {
                        if (nMaxDigits < 0)
                            nMaxDigits = nMinDigits = info.NumberDecimalDigits; // Since we are using digits in our calculation
                        else
                            nMinDigits = nMaxDigits;

                        RoundNumber(ref number, number.scale + nMaxDigits);

                        FormatNumber(ref sb, ref number, nMinDigits, nMaxDigits, info);

                        break;
                    }

                case 'E':
                case 'e':
                    {
                        if (nMaxDigits < 0)
                            nMaxDigits = nMinDigits = 6;
                        else
                            nMinDigits = nMaxDigits;
                        nMaxDigits++;

                        RoundNumber(ref number, nMaxDigits);

                        if (number.sign)
                            sb.Append(info.NegativeSign);

                        FormatScientific(ref sb, ref number, nMinDigits, nMaxDigits, info, format);

                        break;
                    }

                case 'G':
                case 'g':
                    {
                        bool enableRounding = true;
                        if (nMaxDigits < 1)
                        {
                            if (isDecimal && (nMaxDigits == -1))
                            {
                                // Default to 29 digits precision only for G formatting without a precision specifier
                                // This ensures that the PAL code pads out to the correct place even when we use the default precision
                                nMaxDigits = nMinDigits = DecimalPrecision;
                                enableRounding = false;  // Turn off rounding for ECMA compliance to output trailing 0's after decimal as significant
                            }
                            else
                            {
                                // This ensures that the PAL code pads out to the correct place even when we use the default precision
                                nMaxDigits = nMinDigits = number.precision;
                            }
                        }
                        else
                            nMinDigits = nMaxDigits;

                        if (enableRounding) // Don't round for G formatting without precision
                            RoundNumber(ref number, nMaxDigits); // This also fixes up the minus zero case
                        else
                        {
                            if (isDecimal && (number.digits[0] == 0))
                            {
                                // Minus zero should be formatted as 0
                                number.sign = false;
                            }
                        }

                        if (number.sign)
                            sb.Append(info.NegativeSign);

                        FormatGeneral(ref sb, ref number, nMinDigits, nMaxDigits, info, (char)(format - ('G' - 'E')), !enableRounding);

                        break;
                    }

                case 'P':
                case 'p':
                    {
                        if (nMaxDigits < 0)
                            nMaxDigits = nMinDigits = info.PercentDecimalDigits;
                        else
                            nMinDigits = nMaxDigits;
                        number.scale += 2;

                        RoundNumber(ref number, number.scale + nMaxDigits);

                        FormatPercent(ref sb, ref number, nMinDigits, nMaxDigits, info);

                        break;
                    }

                default:
                    throw new FormatException(SR.Argument_BadFormatSpecifier);
            }
        }

        internal static unsafe void NumberToStringFormat(ref ValueStringBuilder sb, ref NumberBuffer number, ReadOnlySpan<char> format, NumberFormatInfo info)
        {
            int digitCount;
            int decimalPos;
            int firstDigit;
            int lastDigit;
            int digPos;
            bool scientific;
            int thousandPos;
            int thousandCount = 0;
            bool thousandSeps;
            int scaleAdjust;
            int adjust;

            int section;
            int src;
            char* dig = number.digits;
            char ch;

            section = FindSection(format, dig[0] == 0 ? 2 : number.sign ? 1 : 0);

            while (true)
            {
                digitCount = 0;
                decimalPos = -1;
                firstDigit = 0x7FFFFFFF;
                lastDigit = 0;
                scientific = false;
                thousandPos = -1;
                thousandSeps = false;
                scaleAdjust = 0;
                src = section;

                fixed (char* pFormat = &MemoryMarshal.GetReference(format))
                {
                    while (src < format.Length && (ch = pFormat[src++]) != 0 && ch != ';')
                    {
                        switch (ch)
                        {
                            case '#':
                                digitCount++;
                                break;
                            case '0':
                                if (firstDigit == 0x7FFFFFFF)
                                    firstDigit = digitCount;
                                digitCount++;
                                lastDigit = digitCount;
                                break;
                            case '.':
                                if (decimalPos < 0)
                                    decimalPos = digitCount;
                                break;
                            case ',':
                                if (digitCount > 0 && decimalPos < 0)
                                {
                                    if (thousandPos >= 0)
                                    {
                                        if (thousandPos == digitCount)
                                        {
                                            thousandCount++;
                                            break;
                                        }
                                        thousandSeps = true;
                                    }
                                    thousandPos = digitCount;
                                    thousandCount = 1;
                                }
                                break;
                            case '%':
                                scaleAdjust += 2;
                                break;
                            case '\x2030':
                                scaleAdjust += 3;
                                break;
                            case '\'':
                            case '"':
                                while (src < format.Length && pFormat[src] != 0 && pFormat[src++] != ch)
                                    ;
                                break;
                            case '\\':
                                if (src < format.Length && pFormat[src] != 0)
                                    src++;
                                break;
                            case 'E':
                            case 'e':
                                if ((src < format.Length && pFormat[src] == '0') ||
                                    (src + 1 < format.Length && (pFormat[src] == '+' || pFormat[src] == '-') && pFormat[src + 1] == '0'))
                                {
                                    while (++src < format.Length && pFormat[src] == '0');
                                    scientific = true;
                                }
                                break;
                        }
                    }
                }

                if (decimalPos < 0)
                    decimalPos = digitCount;

                if (thousandPos >= 0)
                {
                    if (thousandPos == decimalPos)
                        scaleAdjust -= thousandCount * 3;
                    else
                        thousandSeps = true;
                }

                if (dig[0] != 0)
                {
                    number.scale += scaleAdjust;
                    int pos = scientific ? digitCount : number.scale + digitCount - decimalPos;
                    RoundNumber(ref number, pos);
                    if (dig[0] == 0)
                    {
                        src = FindSection(format, 2);
                        if (src != section)
                        {
                            section = src;
                            continue;
                        }
                    }
                }
                else
                {
                    number.sign = false;   // We need to format -0 without the sign set.
                    number.scale = 0;      // Decimals with scale ('0.00') should be rounded.
                }

                break;
            }

            firstDigit = firstDigit < decimalPos ? decimalPos - firstDigit : 0;
            lastDigit = lastDigit > decimalPos ? decimalPos - lastDigit : 0;
            if (scientific)
            {
                digPos = decimalPos;
                adjust = 0;
            }
            else
            {
                digPos = number.scale > decimalPos ? number.scale : decimalPos;
                adjust = number.scale - decimalPos;
            }
            src = section;

            // Adjust can be negative, so we make this an int instead of an unsigned int.
            // Adjust represents the number of characters over the formatting e.g. format string is "0000" and you are trying to
            // format 100000 (6 digits). Means adjust will be 2. On the other hand if you are trying to format 10 adjust will be
            // -2 and we'll need to fixup these digits with 0 padding if we have 0 formatting as in this example.
            Span<int> thousandsSepPos = stackalloc int[4];
            int thousandsSepCtr = -1;

            if (thousandSeps)
            {
                // We need to precompute this outside the number formatting loop
                if (info.NumberGroupSeparator.Length > 0)
                {
                    // We need this array to figure out where to insert the thousands separator. We would have to traverse the string
                    // backwards. PIC formatting always traverses forwards. These indices are precomputed to tell us where to insert
                    // the thousands separator so we can get away with traversing forwards. Note we only have to compute up to digPos.
                    // The max is not bound since you can have formatting strings of the form "000,000..", and this
                    // should handle that case too.

                    int[] groupDigits = info.numberGroupSizes;

                    int groupSizeIndex = 0;     // Index into the groupDigits array.
                    int groupTotalSizeCount = 0;
                    int groupSizeLen = groupDigits.Length;    // The length of groupDigits array.
                    if (groupSizeLen != 0)
                        groupTotalSizeCount = groupDigits[groupSizeIndex];   // The current running total of group size.
                    int groupSize = groupTotalSizeCount;

                    int totalDigits = digPos + ((adjust < 0) ? adjust : 0); // Actual number of digits in o/p
                    int numDigits = (firstDigit > totalDigits) ? firstDigit : totalDigits;
                    while (numDigits > groupTotalSizeCount)
                    {
                        if (groupSize == 0)
                            break;
                        ++thousandsSepCtr;
                        if (thousandsSepCtr >= thousandsSepPos.Length)
                        {
                            var newThousandsSepPos = new int[thousandsSepPos.Length * 2];
                            thousandsSepPos.CopyTo(newThousandsSepPos);
                            thousandsSepPos = newThousandsSepPos;
                        }

                        thousandsSepPos[thousandsSepCtr] = groupTotalSizeCount;
                        if (groupSizeIndex < groupSizeLen - 1)
                        {
                            groupSizeIndex++;
                            groupSize = groupDigits[groupSizeIndex];
                        }
                        groupTotalSizeCount += groupSize;
                    }
                }
            }
            
            if (number.sign && section == 0)
                sb.Append(info.NegativeSign);

            bool decimalWritten = false;

            fixed (char* pFormat = &MemoryMarshal.GetReference(format))
            {
                char* cur = dig;

                while (src < format.Length && (ch = pFormat[src++]) != 0 && ch != ';')
                {
                    if (adjust > 0)
                    {
                        switch (ch)
                        {
                            case '#':
                            case '0':
                            case '.':
                                while (adjust > 0)
                                {
                                    // digPos will be one greater than thousandsSepPos[thousandsSepCtr] since we are at
                                    // the character after which the groupSeparator needs to be appended.
                                    sb.Append(*cur != 0 ? *cur++ : '0');
                                    if (thousandSeps && digPos > 1 && thousandsSepCtr >= 0)
                                    {
                                        if (digPos == thousandsSepPos[thousandsSepCtr] + 1)
                                        {
                                            sb.Append(info.NumberGroupSeparator);
                                            thousandsSepCtr--;
                                        }
                                    }
                                    digPos--;
                                    adjust--;
                                }
                                break;
                        }
                    }

                    switch (ch)
                    {
                        case '#':
                        case '0':
                            {
                                if (adjust < 0)
                                {
                                    adjust++;
                                    ch = digPos <= firstDigit ? '0' : '\0';
                                }
                                else
                                {
                                    ch = *cur != 0 ? *cur++ : digPos > lastDigit ? '0' : '\0';
                                }
                                if (ch != 0)
                                {
                                    sb.Append(ch);
                                    if (thousandSeps && digPos > 1 && thousandsSepCtr >= 0)
                                    {
                                        if (digPos == thousandsSepPos[thousandsSepCtr] + 1)
                                        {
                                            sb.Append(info.NumberGroupSeparator);
                                            thousandsSepCtr--;
                                        }
                                    }
                                }

                                digPos--;
                                break;
                            }
                        case '.':
                            {
                                if (digPos != 0 || decimalWritten)
                                {
                                    // For compatibility, don't echo repeated decimals
                                    break;
                                }
                                // If the format has trailing zeros or the format has a decimal and digits remain
                                if (lastDigit < 0 || (decimalPos < digitCount && *cur != 0))
                                {
                                    sb.Append(info.NumberDecimalSeparator);
                                    decimalWritten = true;
                                }
                                break;
                            }
                        case '\x2030':
                            sb.Append(info.PerMilleSymbol);
                            break;
                        case '%':
                            sb.Append(info.PercentSymbol);
                            break;
                        case ',':
                            break;
                        case '\'':
                        case '"':
                            while (src < format.Length && pFormat[src] != 0 && pFormat[src] != ch)
                                sb.Append(pFormat[src++]);
                            if (src < format.Length && pFormat[src] != 0)
                                src++;
                            break;
                        case '\\':
                            if (src < format.Length && pFormat[src] != 0)
                                sb.Append(pFormat[src++]);
                            break;
                        case 'E':
                        case 'e':
                            {
                                bool positiveSign = false;
                                int i = 0;
                                if (scientific)
                                {
                                    if (src < format.Length && pFormat[src] == '0')
                                    {
                                        // Handles E0, which should format the same as E-0
                                        i++;
                                    }
                                    else if (src+1 < format.Length && pFormat[src] == '+' && pFormat[src + 1] == '0')
                                    {
                                        // Handles E+0
                                        positiveSign = true;
                                    }
                                    else if (src+1 < format.Length && pFormat[src] == '-' && pFormat[src + 1] == '0')
                                    {
                                        // Handles E-0
                                        // Do nothing, this is just a place holder s.t. we don't break out of the loop.
                                    }
                                    else
                                    {
                                        sb.Append(ch);
                                        break;
                                    }

                                    while (++src < format.Length && pFormat[src] == '0')
                                        i++;
                                    if (i > 10)
                                        i = 10;

                                    int exp = dig[0] == 0 ? 0 : number.scale - decimalPos;
                                    FormatExponent(ref sb, info, exp, ch, i, positiveSign);
                                    scientific = false;
                                }
                                else
                                {
                                    sb.Append(ch); // Copy E or e to output
                                    if (src < format.Length)
                                    {
                                        if (pFormat[src] == '+' || pFormat[src] == '-')
                                            sb.Append(pFormat[src++]);
                                        while (src < format.Length && pFormat[src] == '0')
                                            sb.Append(pFormat[src++]);
                                    }
                                }
                                break;
                            }
                        default:
                            sb.Append(ch);
                            break;
                    }
                }
            }
        }

        private static void FormatCurrency(ref ValueStringBuilder sb, ref NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info)
        {
            string fmt = number.sign ?
                s_negCurrencyFormats[info.CurrencyNegativePattern] :
                s_posCurrencyFormats[info.CurrencyPositivePattern];

            foreach (char ch in fmt)
            {
                switch (ch)
                {
                    case '#':
                        FormatFixed(ref sb, ref number, nMinDigits, nMaxDigits, info, info.currencyGroupSizes, info.CurrencyDecimalSeparator, info.CurrencyGroupSeparator);
                        break;
                    case '-':
                        sb.Append(info.NegativeSign);
                        break;
                    case '$':
                        sb.Append(info.CurrencySymbol);
                        break;
                    default:
                        sb.Append(ch);
                        break;
                }
            }
        }

        private static unsafe void FormatFixed(ref ValueStringBuilder sb, ref NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info, int[] groupDigits, string sDecimal, string sGroup)
        {
            int digPos = number.scale;
            char* dig = number.digits;

            if (digPos > 0)
            {
                if (groupDigits != null)
                {
                    int groupSizeIndex = 0;                             // Index into the groupDigits array.
                    int groupSizeCount = groupDigits[groupSizeIndex];   // The current total of group size.
                    int bufferSize = digPos;                            // The length of the result buffer string.
                    int groupSize = 0;                                  // The current group size.

                    // Find out the size of the string buffer for the result.
                    if (groupDigits.Length != 0) // You can pass in 0 length arrays
                    {
                        while (digPos > groupSizeCount)
                        {
                            groupSize = groupDigits[groupSizeIndex];
                            if (groupSize == 0)
                                break;

                            bufferSize += sGroup.Length;
                            if (groupSizeIndex < groupDigits.Length - 1)
                                groupSizeIndex++;

                            groupSizeCount += groupDigits[groupSizeIndex];
                            if (groupSizeCount < 0 || bufferSize < 0)
                                throw new ArgumentOutOfRangeException(); // If we overflow
                        }

                        groupSize = groupSizeCount == 0 ? 0 : groupDigits[0]; // If you passed in an array with one entry as 0, groupSizeCount == 0
                    }

                    groupSizeIndex = 0;
                    int digitCount = 0;
                    int digLength = string.wcslen(dig);
                    int digStart = (digPos < digLength) ? digPos : digLength;
                    fixed (char* spanPtr = &MemoryMarshal.GetReference(sb.AppendSpan(bufferSize)))
                    {
                        char* p = spanPtr + bufferSize - 1;
                        for (int i = digPos - 1; i >= 0; i--)
                        {
                            *(p--) = (i < digStart) ? dig[i] : '0';

                            if (groupSize > 0)
                            {
                                digitCount++;
                                if ((digitCount == groupSize) && (i != 0))
                                {
                                    for (int j = sGroup.Length - 1; j >= 0; j--)
                                        *(p--) = sGroup[j];

                                    if (groupSizeIndex < groupDigits.Length - 1)
                                    {
                                        groupSizeIndex++;
                                        groupSize = groupDigits[groupSizeIndex];
                                    }
                                    digitCount = 0;
                                }
                            }
                        }

                        Debug.Assert(p >= spanPtr - 1, "Underflow");
                        dig += digStart;
                    }
                }
                else
                {
                    do
                    {
                        sb.Append(*dig != 0 ? *dig++ : '0');
                    }
                    while (--digPos > 0);
                }
            }
            else
            {
                sb.Append('0');
            }

            if (nMaxDigits > 0)
            {
                sb.Append(sDecimal);
                if ((digPos < 0) && (nMaxDigits > 0))
                {
                    int zeroes = Math.Min(-digPos, nMaxDigits);
                    sb.Append('0', zeroes);
                    digPos += zeroes;
                    nMaxDigits -= zeroes;
                }

                while (nMaxDigits > 0)
                {
                    sb.Append((*dig != 0) ? *dig++ : '0');
                    nMaxDigits--;
                }
            }
        }

        private static void FormatNumber(ref ValueStringBuilder sb, ref NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info)
        {
            string fmt = number.sign ?
                s_negNumberFormats[info.NumberNegativePattern] :
                PosNumberFormat;

            foreach (char ch in fmt)
            {
                switch (ch)
                {
                    case '#':
                        FormatFixed(ref sb, ref number, nMinDigits, nMaxDigits, info, info.numberGroupSizes, info.NumberDecimalSeparator, info.NumberGroupSeparator);
                        break;
                    case '-':
                        sb.Append(info.NegativeSign);
                        break;
                    default:
                        sb.Append(ch);
                        break;
                }
            }
        }

        private static unsafe void FormatScientific(ref ValueStringBuilder sb, ref NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info, char expChar)
        {
            char* dig = number.digits;

            sb.Append((*dig != 0) ? *dig++ : '0');

            if (nMaxDigits != 1) // For E0 we would like to suppress the decimal point
                sb.Append(info.NumberDecimalSeparator);

            while (--nMaxDigits > 0)
                sb.Append((*dig != 0) ? *dig++ : '0');

            int e = number.digits[0] == 0 ? 0 : number.scale - 1;
            FormatExponent(ref sb, info, e, expChar, 3, true);
        }

        private static unsafe void FormatExponent(ref ValueStringBuilder sb, NumberFormatInfo info, int value, char expChar, int minDigits, bool positiveSign)
        {
            sb.Append(expChar);

            if (value < 0)
            {
                sb.Append(info.NegativeSign);
                value = -value;
            }
            else
            {
                if (positiveSign)
                    sb.Append(info.PositiveSign);
            }

            char* digits = stackalloc char[MaxUInt32DecDigits];
            char* p = UInt32ToDecChars(digits + MaxUInt32DecDigits, (uint)value, minDigits);
            int i = (int)(digits + MaxUInt32DecDigits - p);
            sb.Append(p, (int)(digits + MaxUInt32DecDigits - p));
        }

        private static unsafe void FormatGeneral(ref ValueStringBuilder sb, ref NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info, char expChar, bool bSuppressScientific)
        {
            int digPos = number.scale;
            bool scientific = false;

            if (!bSuppressScientific)
            {
                // Don't switch to scientific notation
                if (digPos > nMaxDigits || digPos < -3)
                {
                    digPos = 1;
                    scientific = true;
                }
            }

            char* dig = number.digits;

            if (digPos > 0)
            {
                do
                {
                    sb.Append((*dig != 0) ? *dig++ : '0');
                } while (--digPos > 0);
            }
            else
            {
                sb.Append('0');
            }

            if (*dig != 0 || digPos < 0)
            {
                sb.Append(info.NumberDecimalSeparator);

                while (digPos < 0)
                {
                    sb.Append('0');
                    digPos++;
                }

                while (*dig != 0)
                    sb.Append(*dig++);
            }

            if (scientific)
                FormatExponent(ref sb, info, number.scale - 1, expChar, 2, true);
        }

        private static void FormatPercent(ref ValueStringBuilder sb, ref NumberBuffer number, int nMinDigits, int nMaxDigits, NumberFormatInfo info)
        {
            string fmt = number.sign ?
                s_negPercentFormats[info.PercentNegativePattern] :
                s_posPercentFormats[info.PercentPositivePattern];

            foreach (char ch in fmt)
            {
                switch (ch)
                {
                    case '#':
                        FormatFixed(ref sb, ref number, nMinDigits, nMaxDigits, info, info.percentGroupSizes, info.PercentDecimalSeparator, info.PercentGroupSeparator);
                        break;
                    case '-':
                        sb.Append(info.NegativeSign);
                        break;
                    case '%':
                        sb.Append(info.PercentSymbol);
                        break;
                    default:
                        sb.Append(ch);
                        break;
                }
            }
        }

        private static unsafe void RoundNumber(ref NumberBuffer number, int pos)
        {
            char* dig = number.digits;

            int i = 0;
            while (i < pos && dig[i] != 0)
                i++;

            if (i == pos && dig[i] >= '5')
            {
                while (i > 0 && dig[i - 1] == '9')
                    i--;

                if (i > 0)
                {
                    dig[i - 1]++;
                }
                else
                {
                    number.scale++;
                    dig[0] = '1';
                    i = 1;
                }
            }
            else
            {
                while (i > 0 && dig[i - 1] == '0')
                    i--;
            }
            if (i == 0)
            {
                number.scale = 0;
                number.sign = false;
            }
            dig[i] = '\0';
        }

        private static unsafe int FindSection(ReadOnlySpan<char> format, int section)
        {
            int src;
            char ch;

            if (section == 0)
                return 0;

            fixed (char* pFormat = &MemoryMarshal.GetReference(format))
            {
                src = 0;
                for (;;)
                {
                    if (src >= format.Length)
                    {
                        return 0;
                    }

                    switch (ch = pFormat[src++])
                    {
                        case '\'':
                        case '"':
                            while (src < format.Length && pFormat[src] != 0 && pFormat[src++] != ch)
                                ;
                            break;
                        case '\\':
                            if (src < format.Length && pFormat[src] != 0)
                                src++;
                            break;
                        case ';':
                            if (--section != 0)
                                break;
                            if (src < format.Length && pFormat[src] != 0 && pFormat[src] != ';')
                                return src;
                            goto case '\0';
                        case '\0':
                            return 0;
                    }
                }
            }
        }

        private static uint Low32(ulong value) => (uint)value;

        private static uint High32(ulong value) => (uint)((value & 0xFFFFFFFF00000000) >> 32);

        private static uint Int64DivMod1E9(ref ulong value)
        {
            uint rem = (uint)(value % 1000000000);
            value /= 1000000000;
            return rem;
        }
    }
}