summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibJS/Runtime/Intl/NumberFormat.cpp
blob: cad3bb1d1efc0f951ca6e98bfa968a37eecc3666 (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
/*
 * Copyright (c) 2021-2022, Tim Flynn <trflynn89@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/Checked.h>
#include <AK/Utf8View.h>
#include <LibCrypto/BigInt/SignedBigInteger.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/BigInt.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/Intl/NumberFormat.h>
#include <LibJS/Runtime/Intl/NumberFormatFunction.h>
#include <LibJS/Runtime/Intl/PluralRules.h>
#include <LibUnicode/CurrencyCode.h>
#include <math.h>
#include <stdlib.h>

namespace JS::Intl {

NumberFormatBase::NumberFormatBase(Object& prototype)
    : Object(prototype)
{
}

// 15 NumberFormat Objects, https://tc39.es/ecma402/#numberformat-objects
NumberFormat::NumberFormat(Object& prototype)
    : NumberFormatBase(prototype)
{
}

void NumberFormat::visit_edges(Cell::Visitor& visitor)
{
    Base::visit_edges(visitor);
    if (m_bound_format)
        visitor.visit(m_bound_format);
}

void NumberFormat::set_style(StringView style)
{
    if (style == "decimal"sv)
        m_style = Style::Decimal;
    else if (style == "percent"sv)
        m_style = Style::Percent;
    else if (style == "currency"sv)
        m_style = Style::Currency;
    else if (style == "unit"sv)
        m_style = Style::Unit;
    else
        VERIFY_NOT_REACHED();
}

StringView NumberFormat::style_string() const
{
    switch (m_style) {
    case Style::Decimal:
        return "decimal"sv;
    case Style::Percent:
        return "percent"sv;
    case Style::Currency:
        return "currency"sv;
    case Style::Unit:
        return "unit"sv;
    default:
        VERIFY_NOT_REACHED();
    }
}

void NumberFormat::set_currency_display(StringView currency_display)
{
    m_resolved_currency_display.clear();

    if (currency_display == "code"sv)
        m_currency_display = CurrencyDisplay::Code;
    else if (currency_display == "symbol"sv)
        m_currency_display = CurrencyDisplay::Symbol;
    else if (currency_display == "narrowSymbol"sv)
        m_currency_display = CurrencyDisplay::NarrowSymbol;
    else if (currency_display == "name"sv)
        m_currency_display = CurrencyDisplay::Name;
    else
        VERIFY_NOT_REACHED();
}

StringView NumberFormat::resolve_currency_display()
{
    if (m_resolved_currency_display.has_value())
        return *m_resolved_currency_display;

    switch (currency_display()) {
    case NumberFormat::CurrencyDisplay::Code:
        m_resolved_currency_display = currency();
        break;
    case NumberFormat::CurrencyDisplay::Symbol:
        m_resolved_currency_display = ::Locale::get_locale_short_currency_mapping(data_locale(), currency());
        break;
    case NumberFormat::CurrencyDisplay::NarrowSymbol:
        m_resolved_currency_display = ::Locale::get_locale_narrow_currency_mapping(data_locale(), currency());
        break;
    case NumberFormat::CurrencyDisplay::Name:
        m_resolved_currency_display = ::Locale::get_locale_numeric_currency_mapping(data_locale(), currency());
        break;
    default:
        VERIFY_NOT_REACHED();
    }

    if (!m_resolved_currency_display.has_value())
        m_resolved_currency_display = currency();

    return *m_resolved_currency_display;
}

StringView NumberFormat::currency_display_string() const
{
    VERIFY(m_currency_display.has_value());

    switch (*m_currency_display) {
    case CurrencyDisplay::Code:
        return "code"sv;
    case CurrencyDisplay::Symbol:
        return "symbol"sv;
    case CurrencyDisplay::NarrowSymbol:
        return "narrowSymbol"sv;
    case CurrencyDisplay::Name:
        return "name"sv;
    default:
        VERIFY_NOT_REACHED();
    }
}

void NumberFormat::set_currency_sign(StringView currency_sign)
{
    if (currency_sign == "standard"sv)
        m_currency_sign = CurrencySign::Standard;
    else if (currency_sign == "accounting"sv)
        m_currency_sign = CurrencySign::Accounting;
    else
        VERIFY_NOT_REACHED();
}

StringView NumberFormat::currency_sign_string() const
{
    VERIFY(m_currency_sign.has_value());

    switch (*m_currency_sign) {
    case CurrencySign::Standard:
        return "standard"sv;
    case CurrencySign::Accounting:
        return "accounting"sv;
    default:
        VERIFY_NOT_REACHED();
    }
}

StringView NumberFormatBase::rounding_type_string() const
{
    switch (m_rounding_type) {
    case RoundingType::SignificantDigits:
        return "significantDigits"sv;
    case RoundingType::FractionDigits:
        return "fractionDigits"sv;
    case RoundingType::MorePrecision:
        return "morePrecision"sv;
    case RoundingType::LessPrecision:
        return "lessPrecision"sv;
    default:
        VERIFY_NOT_REACHED();
    }
}

StringView NumberFormatBase::rounding_mode_string() const
{
    switch (m_rounding_mode) {
    case RoundingMode::Ceil:
        return "ceil"sv;
    case RoundingMode::Expand:
        return "expand"sv;
    case RoundingMode::Floor:
        return "floor"sv;
    case RoundingMode::HalfCeil:
        return "halfCeil"sv;
    case RoundingMode::HalfEven:
        return "halfEven"sv;
    case RoundingMode::HalfExpand:
        return "halfExpand"sv;
    case RoundingMode::HalfFloor:
        return "halfFloor"sv;
    case RoundingMode::HalfTrunc:
        return "halfTrunc"sv;
    case RoundingMode::Trunc:
        return "trunc"sv;
    default:
        VERIFY_NOT_REACHED();
    }
}

void NumberFormatBase::set_rounding_mode(StringView rounding_mode)
{
    if (rounding_mode == "ceil"sv)
        m_rounding_mode = RoundingMode::Ceil;
    else if (rounding_mode == "expand"sv)
        m_rounding_mode = RoundingMode::Expand;
    else if (rounding_mode == "floor"sv)
        m_rounding_mode = RoundingMode::Floor;
    else if (rounding_mode == "halfCeil"sv)
        m_rounding_mode = RoundingMode::HalfCeil;
    else if (rounding_mode == "halfEven"sv)
        m_rounding_mode = RoundingMode::HalfEven;
    else if (rounding_mode == "halfExpand"sv)
        m_rounding_mode = RoundingMode::HalfExpand;
    else if (rounding_mode == "halfFloor"sv)
        m_rounding_mode = RoundingMode::HalfFloor;
    else if (rounding_mode == "halfTrunc"sv)
        m_rounding_mode = RoundingMode::HalfTrunc;
    else if (rounding_mode == "trunc"sv)
        m_rounding_mode = RoundingMode::Trunc;
    else
        VERIFY_NOT_REACHED();
}

StringView NumberFormatBase::trailing_zero_display_string() const
{
    switch (m_trailing_zero_display) {
    case TrailingZeroDisplay::Auto:
        return "auto"sv;
    case TrailingZeroDisplay::StripIfInteger:
        return "stripIfInteger"sv;
    default:
        VERIFY_NOT_REACHED();
    }
}

void NumberFormatBase::set_trailing_zero_display(StringView trailing_zero_display)
{
    if (trailing_zero_display == "auto"sv)
        m_trailing_zero_display = TrailingZeroDisplay::Auto;
    else if (trailing_zero_display == "stripIfInteger"sv)
        m_trailing_zero_display = TrailingZeroDisplay::StripIfInteger;
    else
        VERIFY_NOT_REACHED();
}

Value NumberFormat::use_grouping_to_value(VM& vm) const
{
    switch (m_use_grouping) {
    case UseGrouping::Always:
        return PrimitiveString::create(vm, "always"sv);
    case UseGrouping::Auto:
        return PrimitiveString::create(vm, "auto"sv);
    case UseGrouping::Min2:
        return PrimitiveString::create(vm, "min2"sv);
    case UseGrouping::False:
        return Value(false);
    default:
        VERIFY_NOT_REACHED();
    }
}

void NumberFormat::set_use_grouping(StringOrBoolean const& use_grouping)
{
    use_grouping.visit(
        [this](StringView grouping) {
            if (grouping == "always"sv)
                m_use_grouping = UseGrouping::Always;
            else if (grouping == "auto"sv)
                m_use_grouping = UseGrouping::Auto;
            else if (grouping == "min2"sv)
                m_use_grouping = UseGrouping::Min2;
            else
                VERIFY_NOT_REACHED();
        },
        [this](bool grouping) {
            VERIFY(!grouping);
            m_use_grouping = UseGrouping::False;
        });
}

void NumberFormat::set_notation(StringView notation)
{
    if (notation == "standard"sv)
        m_notation = Notation::Standard;
    else if (notation == "scientific"sv)
        m_notation = Notation::Scientific;
    else if (notation == "engineering"sv)
        m_notation = Notation::Engineering;
    else if (notation == "compact"sv)
        m_notation = Notation::Compact;
    else
        VERIFY_NOT_REACHED();
}

StringView NumberFormat::notation_string() const
{
    switch (m_notation) {
    case Notation::Standard:
        return "standard"sv;
    case Notation::Scientific:
        return "scientific"sv;
    case Notation::Engineering:
        return "engineering"sv;
    case Notation::Compact:
        return "compact"sv;
    default:
        VERIFY_NOT_REACHED();
    }
}

void NumberFormat::set_compact_display(StringView compact_display)
{
    if (compact_display == "short"sv)
        m_compact_display = CompactDisplay::Short;
    else if (compact_display == "long"sv)
        m_compact_display = CompactDisplay::Long;
    else
        VERIFY_NOT_REACHED();
}

StringView NumberFormat::compact_display_string() const
{
    VERIFY(m_compact_display.has_value());

    switch (*m_compact_display) {
    case CompactDisplay::Short:
        return "short"sv;
    case CompactDisplay::Long:
        return "long"sv;
    default:
        VERIFY_NOT_REACHED();
    }
}

void NumberFormat::set_sign_display(StringView sign_display)
{
    if (sign_display == "auto"sv)
        m_sign_display = SignDisplay::Auto;
    else if (sign_display == "never"sv)
        m_sign_display = SignDisplay::Never;
    else if (sign_display == "always"sv)
        m_sign_display = SignDisplay::Always;
    else if (sign_display == "exceptZero"sv)
        m_sign_display = SignDisplay::ExceptZero;
    else if (sign_display == "negative"sv)
        m_sign_display = SignDisplay::Negative;
    else
        VERIFY_NOT_REACHED();
}

StringView NumberFormat::sign_display_string() const
{
    switch (m_sign_display) {
    case SignDisplay::Auto:
        return "auto"sv;
    case SignDisplay::Never:
        return "never"sv;
    case SignDisplay::Always:
        return "always"sv;
    case SignDisplay::ExceptZero:
        return "exceptZero"sv;
    case SignDisplay::Negative:
        return "negative"sv;
    default:
        VERIFY_NOT_REACHED();
    }
}

// 15.5.1 CurrencyDigits ( currency ), https://tc39.es/ecma402/#sec-currencydigits
int currency_digits(StringView currency)
{
    // 1. If the ISO 4217 currency and funds code list contains currency as an alphabetic code, return the minor
    //    unit value corresponding to the currency from the list; otherwise, return 2.
    if (auto currency_code = Unicode::get_currency_code(currency); currency_code.has_value())
        return currency_code->minor_unit.value_or(2);
    return 2;
}

// 15.5.3 FormatNumericToString ( intlObject, x ), https://tc39.es/ecma402/#sec-formatnumberstring
// 1.1.5 FormatNumericToString ( intlObject, x ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-formatnumberstring
FormatResult format_numeric_to_string(NumberFormatBase const& intl_object, MathematicalValue number)
{
    bool is_negative = false;

    // 1. If x is negative-zero, then
    if (number.is_negative_zero()) {
        // a. Let isNegative be true.
        is_negative = true;

        // b. Let x be the mathematical value 0.
        number = MathematicalValue(0.0);
    }

    // 2. Assert: x is a mathematical value.
    VERIFY(number.is_mathematical_value());

    // 3. If x < 0, let isNegative be true; else let isNegative be false.
    // FIXME: Spec issue: this step would override step 1a, see https://github.com/tc39/proposal-intl-numberformat-v3/issues/67
    if (number.is_negative()) {
        is_negative = true;

        // 4. If isNegative, then
        //     a. Let x be -x.
        number.negate();
    }

    // 5. Let unsignedRoundingMode be GetUnsignedRoundingMode(intlObject.[[RoundingMode]], isNegative).
    // FIXME: Spec issue: Intl.PluralRules does not have [[RoundingMode]], see https://github.com/tc39/proposal-intl-numberformat-v3/issues/103
    Optional<NumberFormat::UnsignedRoundingMode> unsigned_rounding_mode;
    if (intl_object.rounding_mode() != NumberFormat::RoundingMode::Invalid)
        unsigned_rounding_mode = get_unsigned_rounding_mode(intl_object.rounding_mode(), is_negative);

    RawFormatResult result {};

    switch (intl_object.rounding_type()) {
    // 6. If intlObject.[[RoundingType]] is significantDigits, then
    case NumberFormatBase::RoundingType::SignificantDigits:
        // a. Let result be ToRawPrecision(x, intlObject.[[MinimumSignificantDigits]], intlObject.[[MaximumSignificantDigits]], unsignedRoundingMode).
        result = to_raw_precision(number, intl_object.min_significant_digits(), intl_object.max_significant_digits(), unsigned_rounding_mode);
        break;

    // 7. Else if intlObject.[[RoundingType]] is fractionDigits, then
    case NumberFormatBase::RoundingType::FractionDigits:
        // a. Let result be ToRawFixed(x, intlObject.[[MinimumFractionDigits]], intlObject.[[MaximumFractionDigits]], intlObject.[[RoundingIncrement]], unsignedRoundingMode).
        result = to_raw_fixed(number, intl_object.min_fraction_digits(), intl_object.max_fraction_digits(), intl_object.rounding_increment(), unsigned_rounding_mode);
        break;

    // 8. Else,
    case NumberFormatBase::RoundingType::MorePrecision:
    case NumberFormatBase::RoundingType::LessPrecision: {
        // a. Let sResult be ToRawPrecision(x, intlObject.[[MinimumSignificantDigits]], intlObject.[[MaximumSignificantDigits]], unsignedRoundingMode).
        auto significant_result = to_raw_precision(number, intl_object.min_significant_digits(), intl_object.max_significant_digits(), unsigned_rounding_mode);

        // b. Let fResult be ToRawFixed(x, intlObject.[[MinimumFractionDigits]], intlObject.[[MaximumFractionDigits]], intlObject.[[RoundingIncrement]], unsignedRoundingMode).
        auto fraction_result = to_raw_fixed(number, intl_object.min_fraction_digits(), intl_object.max_fraction_digits(), intl_object.rounding_increment(), unsigned_rounding_mode);

        // c. If intlObj.[[RoundingType]] is morePrecision, then
        if (intl_object.rounding_type() == NumberFormatBase::RoundingType::MorePrecision) {
            // i. If sResult.[[RoundingMagnitude]] ≤ fResult.[[RoundingMagnitude]], then
            if (significant_result.rounding_magnitude <= fraction_result.rounding_magnitude) {
                // 1. Let result be sResult.
                result = move(significant_result);
            }
            // ii. Else,
            else {
                // 2. Let result be fResult.
                result = move(fraction_result);
            }
        }
        // d. Else,
        else {
            // i. Assert: intlObj.[[RoundingType]] is lessPrecision.
            VERIFY(intl_object.rounding_type() == NumberFormatBase::RoundingType::LessPrecision);

            // ii. If sResult.[[RoundingMagnitude]] ≤ fResult.[[RoundingMagnitude]], then
            if (significant_result.rounding_magnitude <= fraction_result.rounding_magnitude) {
                // 1. Let result be fResult.
                result = move(fraction_result);
            }
            // iii. Else,
            else {
                // 1. Let result be sResult.
                result = move(significant_result);
            }
        }

        break;
    }

    default:
        VERIFY_NOT_REACHED();
    }

    // 9. Let x be result.[[RoundedNumber]].
    number = move(result.rounded_number);

    // 10. Let string be result.[[FormattedString]].
    auto string = move(result.formatted_string);

    // 11. If intlObject.[[TrailingZeroDisplay]] is "stripIfInteger" and x modulo 1 = 0, then
    if ((intl_object.trailing_zero_display() == NumberFormat::TrailingZeroDisplay::StripIfInteger) && number.modulo_is_zero(1)) {
        // a. If string contains ".", then
        if (auto index = string.find('.'); index.has_value()) {
            // i. Set string to the substring of string from index 0 to the index of ".".
            string = string.substring(0, *index);
        }
    }

    // 12. Let int be result.[[IntegerDigitsCount]].
    int digits = result.digits;

    // 13. Let minInteger be intlObject.[[MinimumIntegerDigits]].
    int min_integer = intl_object.min_integer_digits();

    // 14. If int < minInteger, then
    if (digits < min_integer) {
        // a. Let forwardZeros be the String consisting of minInteger–int occurrences of the character "0".
        auto forward_zeros = DeprecatedString::repeated('0', min_integer - digits);

        // b. Set string to the string-concatenation of forwardZeros and string.
        string = DeprecatedString::formatted("{}{}", forward_zeros, string);
    }

    // 15. If isNegative and x is 0, then
    if (is_negative && number.is_zero()) {
        // a. Let x be -0.
        number = MathematicalValue { MathematicalValue::Symbol::NegativeZero };
    }
    // 16. Else if isNegative, then
    else if (is_negative) {
        // b. Let x be -x.
        number.negate();
    }

    // 17. Return the Record { [[RoundedNumber]]: x, [[FormattedString]]: string }.
    return { move(string), move(number) };
}

// 15.5.4 PartitionNumberPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-partitionnumberpattern
// 1.1.6 PartitionNumberPattern ( numberFormat, x ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-partitionnumberpattern
Vector<PatternPartition> partition_number_pattern(VM& vm, NumberFormat& number_format, MathematicalValue number)
{
    // 1. Let exponent be 0.
    int exponent = 0;

    DeprecatedString formatted_string;

    // 2. If x is not-a-number, then
    if (number.is_nan()) {
        // a. Let n be an implementation- and locale-dependent (ILD) String value indicating the NaN value.
        formatted_string = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::NaN).value_or("NaN"sv);
    }
    // 3. Else if x is positive-infinity, then
    else if (number.is_positive_infinity()) {
        // a. Let n be an ILD String value indicating positive infinity.
        formatted_string = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Infinity).value_or("infinity"sv);
    }
    // 4. Else if x is negative-infinity, then
    else if (number.is_negative_infinity()) {
        // a. Let n be an ILD String value indicating negative infinity.
        // NOTE: The CLDR does not contain unique strings for negative infinity. The negative sign will
        //       be inserted by the pattern returned from GetNumberFormatPattern.
        formatted_string = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Infinity).value_or("infinity"sv);
    }
    // 5. Else,
    else {
        // a. If x is not negative-zero,
        if (!number.is_negative_zero()) {
            // i. Assert: x is a mathematical value.
            VERIFY(number.is_mathematical_value());

            // ii. If numberFormat.[[Style]] is "percent", let x be 100 × x.
            if (number_format.style() == NumberFormat::Style::Percent)
                number = number.multiplied_by(100);

            // iii. Let exponent be ComputeExponent(numberFormat, x).
            exponent = compute_exponent(number_format, number);

            // iv. Let x be x × 10^-exponent.
            number = number.multiplied_by_power(-exponent);
        }

        // b. Let formatNumberResult be FormatNumericToString(numberFormat, x).
        auto format_number_result = format_numeric_to_string(number_format, move(number));

        // c. Let n be formatNumberResult.[[FormattedString]].
        formatted_string = move(format_number_result.formatted_string);

        // d. Let x be formatNumberResult.[[RoundedNumber]].
        number = move(format_number_result.rounded_number);
    }

    ::Locale::NumberFormat found_pattern {};

    // 6. Let pattern be GetNumberFormatPattern(numberFormat, x).
    auto pattern = get_number_format_pattern(vm, number_format, number, found_pattern);
    if (!pattern.has_value())
        return {};

    // 7. Let result be a new empty List.
    Vector<PatternPartition> result;

    // 8. Let patternParts be PartitionPattern(pattern).
    auto pattern_parts = pattern->visit([](auto const& p) { return partition_pattern(p); });

    // 9. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
    for (auto& pattern_part : pattern_parts) {
        // a. Let p be patternPart.[[Type]].
        auto part = pattern_part.type;

        // b. If p is "literal", then
        if (part == "literal"sv) {
            // i. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
            result.append({ "literal"sv, move(pattern_part.value) });
        }

        // c. Else if p is equal to "number", then
        else if (part == "number"sv) {
            // i. Let notationSubParts be PartitionNotationSubPattern(numberFormat, x, n, exponent).
            auto notation_sub_parts = partition_notation_sub_pattern(number_format, number, formatted_string, exponent);
            // ii. Append all elements of notationSubParts to result.
            result.extend(move(notation_sub_parts));
        }

        // d. Else if p is equal to "plusSign", then
        else if (part == "plusSign"sv) {
            // i. Let plusSignSymbol be the ILND String representing the plus sign.
            auto plus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::PlusSign).value_or("+"sv);
            // ii. Append a new Record { [[Type]]: "plusSign", [[Value]]: plusSignSymbol } as the last element of result.
            result.append({ "plusSign"sv, plus_sign_symbol });
        }

        // e. Else if p is equal to "minusSign", then
        else if (part == "minusSign"sv) {
            // i. Let minusSignSymbol be the ILND String representing the minus sign.
            auto minus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::MinusSign).value_or("-"sv);
            // ii. Append a new Record { [[Type]]: "minusSign", [[Value]]: minusSignSymbol } as the last element of result.
            result.append({ "minusSign"sv, minus_sign_symbol });
        }

        // f. Else if p is equal to "percentSign" and numberFormat.[[Style]] is "percent", then
        else if ((part == "percentSign"sv) && (number_format.style() == NumberFormat::Style::Percent)) {
            // i. Let percentSignSymbol be the ILND String representing the percent sign.
            auto percent_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::PercentSign).value_or("%"sv);
            // ii. Append a new Record { [[Type]]: "percentSign", [[Value]]: percentSignSymbol } as the last element of result.
            result.append({ "percentSign"sv, percent_sign_symbol });
        }

        // g. Else if p is equal to "unitPrefix" and numberFormat.[[Style]] is "unit", then
        // h. Else if p is equal to "unitSuffix" and numberFormat.[[Style]] is "unit", then
        else if ((part.starts_with("unitIdentifier:"sv)) && (number_format.style() == NumberFormat::Style::Unit)) {
            // Note: Our implementation combines "unitPrefix" and "unitSuffix" into one field, "unitIdentifier".

            auto identifier_index = part.substring_view("unitIdentifier:"sv.length()).to_uint();
            VERIFY(identifier_index.has_value());

            // i. Let unit be numberFormat.[[Unit]].
            // ii. Let unitDisplay be numberFormat.[[UnitDisplay]].
            // iii. Let mu be an ILD String value representing unit before x in unitDisplay form, which may depend on x in languages having different plural forms.
            auto unit_identifier = found_pattern.identifiers[*identifier_index];

            // iv. Append a new Record { [[Type]]: "unit", [[Value]]: mu } as the last element of result.
            result.append({ "unit"sv, unit_identifier });
        }

        // i. Else if p is equal to "currencyCode" and numberFormat.[[Style]] is "currency", then
        // j. Else if p is equal to "currencyPrefix" and numberFormat.[[Style]] is "currency", then
        // k. Else if p is equal to "currencySuffix" and numberFormat.[[Style]] is "currency", then
        //
        // Note: Our implementation manipulates the format string to inject/remove spacing around the
        //       currency code during GetNumberFormatPattern so that we do not have to do currency
        //       display / plurality lookups more than once.
        else if ((part == "currency"sv) && (number_format.style() == NumberFormat::Style::Currency)) {
            result.append({ "currency"sv, number_format.resolve_currency_display() });
        }

        // l. Else,
        else {
            // i. Let unknown be an ILND String based on x and p.
            // ii. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.

            // LibUnicode doesn't generate any "unknown" patterns.
            VERIFY_NOT_REACHED();
        }
    }

    // 10. Return result.
    return result;
}

static Vector<StringView> separate_integer_into_groups(::Locale::NumberGroupings const& grouping_sizes, StringView integer, NumberFormat::UseGrouping use_grouping)
{
    Utf8View utf8_integer { integer };
    if (utf8_integer.length() <= grouping_sizes.primary_grouping_size)
        return { integer };

    size_t index = utf8_integer.length() - grouping_sizes.primary_grouping_size;

    switch (use_grouping) {
    case NumberFormat::UseGrouping::Min2:
        if (utf8_integer.length() < 5)
            return { integer };
        break;

    case NumberFormat::UseGrouping::Auto:
        if (index < grouping_sizes.minimum_grouping_digits)
            return { integer };
        break;

    case NumberFormat::UseGrouping::Always:
        break;

    default:
        VERIFY_NOT_REACHED();
    }

    Vector<StringView> groups;

    auto add_group = [&](size_t index, size_t length) {
        groups.prepend(utf8_integer.unicode_substring_view(index, length).as_string());
    };

    add_group(index, grouping_sizes.primary_grouping_size);

    while (index > grouping_sizes.secondary_grouping_size) {
        index -= grouping_sizes.secondary_grouping_size;
        add_group(index, grouping_sizes.secondary_grouping_size);
    }

    if (index > 0)
        add_group(0, index);

    return groups;
}

// 15.5.5 PartitionNotationSubPattern ( numberFormat, x, n, exponent ), https://tc39.es/ecma402/#sec-partitionnotationsubpattern
// 1.1.7 PartitionNotationSubPattern ( numberFormat, x, n, exponent ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-partitionnotationsubpattern
Vector<PatternPartition> partition_notation_sub_pattern(NumberFormat& number_format, MathematicalValue const& number, DeprecatedString formatted_string, int exponent)
{
    // 1. Let result be a new empty List.
    Vector<PatternPartition> result;

    auto grouping_sizes = ::Locale::get_number_system_groupings(number_format.data_locale(), number_format.numbering_system());
    if (!grouping_sizes.has_value())
        return {};

    // 2. If x is NaN, then
    if (number.is_nan()) {
        // a. Append a new Record { [[Type]]: "nan", [[Value]]: n } as the last element of result.
        result.append({ "nan"sv, move(formatted_string) });
    }
    // 3. Else if x is a non-finite Number, then
    else if (number.is_positive_infinity() || number.is_negative_infinity()) {
        // a. Append a new Record { [[Type]]: "infinity", [[Value]]: n } as the last element of result.
        result.append({ "infinity"sv, move(formatted_string) });
    }
    // 4. Else,
    else {
        // a. Let notationSubPattern be GetNotationSubPattern(numberFormat, exponent).
        auto notation_sub_pattern = get_notation_sub_pattern(number_format, exponent);
        if (!notation_sub_pattern.has_value())
            return {};

        // b. Let patternParts be PartitionPattern(notationSubPattern).
        auto pattern_parts = partition_pattern(*notation_sub_pattern);

        // c. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
        for (auto& pattern_part : pattern_parts) {
            // i. Let p be patternPart.[[Type]].
            auto part = pattern_part.type;

            // ii. If p is "literal", then
            if (part == "literal"sv) {
                // 1. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
                result.append({ "literal"sv, move(pattern_part.value) });
            }
            // iii. Else if p is equal to "number", then
            else if (part == "number"sv) {
                // 1. If the numberFormat.[[NumberingSystem]] matches one of the values in the "Numbering System" column of Table 12 below, then
                //     a. Let digits be a List whose 10 String valued elements are the UTF-16 string representations of the 10 digits specified in the "Digits" column of the matching row in Table 12.
                //     b. Replace each digit in n with the value of digits[digit].
                // 2. Else use an implementation dependent algorithm to map n to the appropriate representation of n in the given numbering system.
                formatted_string = ::Locale::replace_digits_for_number_system(number_format.numbering_system(), formatted_string);

                // 3. Let decimalSepIndex be StringIndexOf(n, ".", 0).
                auto decimal_sep_index = formatted_string.find('.');

                StringView integer;
                Optional<StringView> fraction;

                // 4. If decimalSepIndex > 0, then
                if (decimal_sep_index.has_value() && (*decimal_sep_index > 0)) {
                    // a. Let integer be the substring of n from position 0, inclusive, to position decimalSepIndex, exclusive.
                    integer = formatted_string.substring_view(0, *decimal_sep_index);
                    // b. Let fraction be the substring of n from position decimalSepIndex, exclusive, to the end of n.
                    fraction = formatted_string.substring_view(*decimal_sep_index + 1);
                }
                // 5. Else,
                else {
                    // a. Let integer be n.
                    integer = formatted_string;
                    // b. Let fraction be undefined.
                }

                // 6. If the numberFormat.[[UseGrouping]] is false, then
                if (number_format.use_grouping() == NumberFormat::UseGrouping::False) {
                    // a. Append a new Record { [[Type]]: "integer", [[Value]]: integer } as the last element of result.
                    result.append({ "integer"sv, integer });
                }
                // 7. Else,
                else {
                    // a. Let groupSepSymbol be the implementation-, locale-, and numbering system-dependent (ILND) String representing the grouping separator.
                    auto group_sep_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Group).value_or(","sv);

                    // b. Let groups be a List whose elements are, in left to right order, the substrings defined by ILND set of locations within the integer, which may depend on the value of numberFormat.[[UseGrouping]].
                    auto groups = separate_integer_into_groups(*grouping_sizes, integer, number_format.use_grouping());

                    // c. Assert: The number of elements in groups List is greater than 0.
                    VERIFY(!groups.is_empty());

                    // d. Repeat, while groups List is not empty,
                    while (!groups.is_empty()) {
                        // i. Remove the first element from groups and let integerGroup be the value of that element.
                        auto integer_group = groups.take_first();

                        // ii. Append a new Record { [[Type]]: "integer", [[Value]]: integerGroup } as the last element of result.
                        result.append({ "integer"sv, integer_group });

                        // iii. If groups List is not empty, then
                        if (!groups.is_empty()) {
                            // i. Append a new Record { [[Type]]: "group", [[Value]]: groupSepSymbol } as the last element of result.
                            result.append({ "group"sv, group_sep_symbol });
                        }
                    }
                }

                // 8. If fraction is not undefined, then
                if (fraction.has_value()) {
                    // a. Let decimalSepSymbol be the ILND String representing the decimal separator.
                    auto decimal_sep_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Decimal).value_or("."sv);
                    // b. Append a new Record { [[Type]]: "decimal", [[Value]]: decimalSepSymbol } as the last element of result.
                    result.append({ "decimal"sv, decimal_sep_symbol });
                    // c. Append a new Record { [[Type]]: "fraction", [[Value]]: fraction } as the last element of result.
                    result.append({ "fraction"sv, fraction.release_value() });
                }
            }
            // iv. Else if p is equal to "compactSymbol", then
            // v. Else if p is equal to "compactName", then
            else if (part.starts_with("compactIdentifier:"sv)) {
                // Note: Our implementation combines "compactSymbol" and "compactName" into one field, "compactIdentifier".

                auto identifier_index = part.substring_view("compactIdentifier:"sv.length()).to_uint();
                VERIFY(identifier_index.has_value());

                // 1. Let compactSymbol be an ILD string representing exponent in short form, which may depend on x in languages having different plural forms. The implementation must be able to provide this string, or else the pattern would not have a "{compactSymbol}" placeholder.
                auto compact_identifier = number_format.compact_format().identifiers[*identifier_index];

                // 2. Append a new Record { [[Type]]: "compact", [[Value]]: compactSymbol } as the last element of result.
                result.append({ "compact"sv, compact_identifier });
            }
            // vi. Else if p is equal to "scientificSeparator", then
            else if (part == "scientificSeparator"sv) {
                // 1. Let scientificSeparator be the ILND String representing the exponent separator.
                auto scientific_separator = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Exponential).value_or("E"sv);
                // 2. Append a new Record { [[Type]]: "exponentSeparator", [[Value]]: scientificSeparator } as the last element of result.
                result.append({ "exponentSeparator"sv, scientific_separator });
            }
            // vii. Else if p is equal to "scientificExponent", then
            else if (part == "scientificExponent"sv) {
                // 1. If exponent < 0, then
                if (exponent < 0) {
                    // a. Let minusSignSymbol be the ILND String representing the minus sign.
                    auto minus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::MinusSign).value_or("-"sv);

                    // b. Append a new Record { [[Type]]: "exponentMinusSign", [[Value]]: minusSignSymbol } as the last element of result.
                    result.append({ "exponentMinusSign"sv, minus_sign_symbol });

                    // c. Let exponent be -exponent.
                    exponent *= -1;
                }

                // 2. Let exponentResult be ToRawFixed(exponent, 0, 0, 1, undefined).
                auto exponent_value = MathematicalValue { static_cast<double>(exponent) };
                auto exponent_result = to_raw_fixed(exponent_value, 0, 0, 1, {});

                // FIXME: The spec does not say to do this, but all of major engines perform this replacement.
                //        Without this, formatting with non-Latin numbering systems will produce non-localized results.
                exponent_result.formatted_string = ::Locale::replace_digits_for_number_system(number_format.numbering_system(), exponent_result.formatted_string);

                // 3. Append a new Record { [[Type]]: "exponentInteger", [[Value]]: exponentResult.[[FormattedString]] } as the last element of result.
                result.append({ "exponentInteger"sv, move(exponent_result.formatted_string) });
            }
            // viii. Else,
            else {
                // 1. Let unknown be an ILND String based on x and p.
                // 2. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.

                // LibUnicode doesn't generate any "unknown" patterns.
                VERIFY_NOT_REACHED();
            }
        }
    }

    // 5. Return result.
    return result;
}

// 15.5.6 FormatNumeric ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumber
DeprecatedString format_numeric(VM& vm, NumberFormat& number_format, MathematicalValue number)
{
    // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
    // Note: Our implementation of PartitionNumberPattern does not throw.
    auto parts = partition_number_pattern(vm, number_format, move(number));

    // 2. Let result be the empty String.
    StringBuilder result;

    // 3. For each Record { [[Type]], [[Value]] } part in parts, do
    for (auto& part : parts) {
        // a. Set result to the string-concatenation of result and part.[[Value]].
        result.append(move(part.value));
    }

    // 4. Return result.
    return result.build();
}

// 15.5.7 FormatNumericToParts ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumbertoparts
Array* format_numeric_to_parts(VM& vm, NumberFormat& number_format, MathematicalValue number)
{
    auto& realm = *vm.current_realm();

    // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
    // Note: Our implementation of PartitionNumberPattern does not throw.
    auto parts = partition_number_pattern(vm, number_format, move(number));

    // 2. Let result be ! ArrayCreate(0).
    auto result = MUST(Array::create(realm, 0));

    // 3. Let n be 0.
    size_t n = 0;

    // 4. For each Record { [[Type]], [[Value]] } part in parts, do
    for (auto& part : parts) {
        // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
        auto* object = Object::create(realm, realm.intrinsics().object_prototype());

        // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
        MUST(object->create_data_property_or_throw(vm.names.type, PrimitiveString::create(vm, part.type)));

        // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
        MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(vm, move(part.value))));

        // d. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
        MUST(result->create_data_property_or_throw(n, object));

        // e. Increment n by 1.
        ++n;
    }

    // 5. Return result.
    return result;
}

static DeprecatedString cut_trailing_zeroes(StringView string, int cut)
{
    // These steps are exactly the same between ToRawPrecision and ToRawFixed.

    // Repeat, while cut > 0 and the last character of m is "0",
    while ((cut > 0) && string.ends_with('0')) {
        // Remove the last character from m.
        string = string.substring_view(0, string.length() - 1);

        // Decrease cut by 1.
        --cut;
    }

    // If the last character of m is ".", then
    if (string.ends_with('.')) {
        // Remove the last character from m.
        string = string.substring_view(0, string.length() - 1);
    }

    return string.to_deprecated_string();
}

enum class PreferredResult {
    LessThanNumber,
    GreaterThanNumber,
};

// ToRawPrecisionFn, https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#eqn-ToRawPrecisionFn
static auto to_raw_precision_function(MathematicalValue const& number, int precision, PreferredResult mode)
{
    struct {
        MathematicalValue number;
        int exponent { 0 };
        MathematicalValue rounded;
    } result {};

    result.exponent = number.logarithmic_floor();

    if (number.is_number()) {
        result.number = number.divided_by_power(result.exponent - precision + 1);

        switch (mode) {
        case PreferredResult::LessThanNumber:
            result.number = MathematicalValue { floor(result.number.as_number()) };
            break;
        case PreferredResult::GreaterThanNumber:
            result.number = MathematicalValue { ceil(result.number.as_number()) };
            break;
        }
    } else {
        // NOTE: In order to round the BigInt to the proper precision, this computation is initially off by a
        //       factor of 10. This lets us inspect the ones digit and then round up if needed.
        result.number = number.divided_by_power(result.exponent - precision);

        // FIXME: Can we do this without string conversion?
        auto digits = result.number.to_deprecated_string();
        auto digit = digits.substring_view(digits.length() - 1);

        result.number = result.number.divided_by(10);

        if (mode == PreferredResult::GreaterThanNumber && digit.to_uint().value() != 0)
            result.number = result.number.plus(1);
    }

    result.rounded = result.number.multiplied_by_power(result.exponent - precision + 1);
    return result;
}

// 15.5.8 ToRawPrecision ( x, minPrecision, maxPrecision ), https://tc39.es/ecma402/#sec-torawprecision
// 1.1.10 ToRawPrecision ( x, minPrecision, maxPrecision, unsignedRoundingMode ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-torawprecision
RawFormatResult to_raw_precision(MathematicalValue const& number, int min_precision, int max_precision, Optional<NumberFormat::UnsignedRoundingMode> const& unsigned_rounding_mode)
{
    RawFormatResult result {};

    // 1. Let p be maxPrecision.
    int precision = max_precision;
    int exponent = 0;

    // 2. If x = 0, then
    if (number.is_zero()) {
        // a. Let m be the String consisting of p occurrences of the character "0".
        result.formatted_string = DeprecatedString::repeated('0', precision);

        // b. Let e be 0.
        exponent = 0;

        // c. Let xFinal be 0.
        result.rounded_number = MathematicalValue { 0.0 };
    }
    // 3. Else,
    else {
        // a. Let n1 and e1 each be an integer and r1 a mathematical value, with r1 = ToRawPrecisionFn(n1, e1, p), such that r1 ≤ x and r1 is maximized.
        auto [number1, exponent1, rounded1] = to_raw_precision_function(number, precision, PreferredResult::LessThanNumber);

        // b. Let n2 and e2 each be an integer and r2 a mathematical value, with r2 = ToRawPrecisionFn(n2, e2, p), such that r2 ≥ x and r2 is minimized.
        auto [number2, exponent2, rounded2] = to_raw_precision_function(number, precision, PreferredResult::GreaterThanNumber);

        // c. Let r be ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode).
        auto rounded = apply_unsigned_rounding_mode(number, rounded1, rounded2, unsigned_rounding_mode);

        MathematicalValue n;

        // d. If r is r1, then
        if (rounded == RoundingDecision::LowerValue) {
            // i. Let n be n1.
            n = move(number1);

            // ii. Let e be e1.
            exponent = exponent1;

            // iii. Let xFinal be r1.
            result.rounded_number = move(rounded1);
        }
        // e. Else,
        else {
            // i. Let n be n2.
            n = move(number2);

            // ii. Let e be e2.
            exponent = exponent2;

            // iii. Let xFinal be r2.
            result.rounded_number = move(rounded2);
        }

        // f. Let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
        result.formatted_string = n.to_deprecated_string();
    }

    // 4. If e ≥ p–1, then
    if (exponent >= (precision - 1)) {
        // a. Let m be the string-concatenation of m and e–p+1 occurrences of the character "0".
        result.formatted_string = DeprecatedString::formatted(
            "{}{}",
            result.formatted_string,
            DeprecatedString::repeated('0', exponent - precision + 1));

        // b. Let int be e+1.
        result.digits = exponent + 1;
    }
    // 5. Else if e ≥ 0, then
    else if (exponent >= 0) {
        // a. Let m be the string-concatenation of the first e+1 characters of m, the character ".", and the remaining p–(e+1) characters of m.
        result.formatted_string = DeprecatedString::formatted(
            "{}.{}",
            result.formatted_string.substring_view(0, exponent + 1),
            result.formatted_string.substring_view(exponent + 1));

        // b. Let int be e+1.
        result.digits = exponent + 1;
    }
    // 6. Else,
    else {
        // a. Assert: e < 0.
        // b. Let m be the string-concatenation of "0.", –(e+1) occurrences of the character "0", and m.
        result.formatted_string = DeprecatedString::formatted(
            "0.{}{}",
            DeprecatedString::repeated('0', -1 * (exponent + 1)),
            result.formatted_string);

        // c. Let int be 1.
        result.digits = 1;
    }

    // 7. If m contains the character ".", and maxPrecision > minPrecision, then
    if (result.formatted_string.contains('.') && (max_precision > min_precision)) {
        // a. Let cut be maxPrecision – minPrecision.
        int cut = max_precision - min_precision;

        // Steps 8b-8c are implemented by cut_trailing_zeroes.
        result.formatted_string = cut_trailing_zeroes(result.formatted_string, cut);
    }

    // 8. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int, [[RoundingMagnitude]]: e–p+1 }.
    result.rounding_magnitude = exponent - precision + 1;
    return result;
}

// ToRawFixedFn, https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#eqn-ToRawFixedFn
static auto to_raw_fixed_function(MathematicalValue const& number, int fraction, int rounding_increment, PreferredResult mode)
{
    struct {
        MathematicalValue number;
        MathematicalValue rounded;
    } result {};

    if (number.is_number()) {
        result.number = number.multiplied_by_power(fraction);

        switch (mode) {
        case PreferredResult::LessThanNumber:
            result.number = MathematicalValue { floor(result.number.as_number()) };
            break;
        case PreferredResult::GreaterThanNumber:
            result.number = MathematicalValue { ceil(result.number.as_number()) };
            break;
        }
    } else {
        // NOTE: In order to round the BigInt to the proper precision, this computation is initially off by a
        //       factor of 10. This lets us inspect the ones digit and then round up if needed.
        result.number = number.multiplied_by_power(fraction - 1);

        // FIXME: Can we do this without string conversion?
        auto digits = result.number.to_deprecated_string();
        auto digit = digits.substring_view(digits.length() - 1);

        result.number = result.number.multiplied_by(10);

        if (mode == PreferredResult::GreaterThanNumber && digit.to_uint().value() != 0)
            result.number = result.number.plus(1);
    }

    while (!result.number.modulo_is_zero(rounding_increment)) {
        switch (mode) {
        case PreferredResult::LessThanNumber:
            result.number = result.number.minus(1);
            break;
        case PreferredResult::GreaterThanNumber:
            result.number = result.number.plus(1);
            break;
        }
    }

    result.rounded = result.number.divided_by_power(fraction);
    return result;
}

// 15.5.9 ToRawFixed ( x, minInteger, minFraction, maxFraction ), https://tc39.es/ecma402/#sec-torawfixed
// 1.1.11 ToRawFixed ( x, minFraction, maxFraction, roundingIncrement, unsignedRoundingMode ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-torawfixed
RawFormatResult to_raw_fixed(MathematicalValue const& number, int min_fraction, int max_fraction, int rounding_increment, Optional<NumberFormat::UnsignedRoundingMode> const& unsigned_rounding_mode)
{
    RawFormatResult result {};

    // 1. Let f be maxFraction.
    int fraction = max_fraction;

    // 2. Let n1 be an integer and r1 a mathematical value, with r1 = ToRawFixedFn(n1, f), such that n1 modulo roundingIncrement = 0, r1 ≤ x, and r1 is maximized.
    auto [number1, rounded1] = to_raw_fixed_function(number, fraction, rounding_increment, PreferredResult::LessThanNumber);

    // 3. Let n2 be an integer and r2 a mathematical value, with r2 = ToRawFixedFn(n2, f), such that n2 modulo roundingIncrement = 0, r2 ≥ x, and r2 is minimized.
    auto [number2, rounded2] = to_raw_fixed_function(number, fraction, rounding_increment, PreferredResult::GreaterThanNumber);

    // 4. Let r be ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode).
    auto rounded = apply_unsigned_rounding_mode(number, rounded1, rounded2, unsigned_rounding_mode);

    MathematicalValue n;

    // 5. If r is r1, then
    if (rounded == RoundingDecision::LowerValue) {
        // a. Let n be n1.
        n = move(number1);

        // b. Let xFinal be r1.
        result.rounded_number = move(rounded1);
    }
    // 6. Else,
    else {
        // a. Let n be n2.
        n = move(number2);

        // b. Let xFinal be r2.
        result.rounded_number = move(rounded2);
    }

    // 7. If n = 0, let m be "0". Otherwise, let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
    result.formatted_string = n.is_zero() ? DeprecatedString("0"sv) : n.to_deprecated_string();

    // 8. If f ≠ 0, then
    if (fraction != 0) {
        // a. Let k be the number of characters in m.
        auto decimals = result.formatted_string.length();

        // b. If k ≤ f, then
        if (decimals <= static_cast<size_t>(fraction)) {
            // i. Let z be the String value consisting of f+1–k occurrences of the character "0".
            auto zeroes = DeprecatedString::repeated('0', fraction + 1 - decimals);

            // ii. Let m be the string-concatenation of z and m.
            result.formatted_string = DeprecatedString::formatted("{}{}", zeroes, result.formatted_string);

            // iii. Let k be f+1.
            decimals = fraction + 1;
        }

        // c. Let a be the first k–f characters of m, and let b be the remaining f characters of m.
        auto a = result.formatted_string.substring_view(0, decimals - fraction);
        auto b = result.formatted_string.substring_view(decimals - fraction, fraction);

        // d. Let m be the string-concatenation of a, ".", and b.
        result.formatted_string = DeprecatedString::formatted("{}.{}", a, b);

        // e. Let int be the number of characters in a.
        result.digits = a.length();
    }
    // 9. Else, let int be the number of characters in m.
    else {
        result.digits = result.formatted_string.length();
    }

    // 10. Let cut be maxFraction – minFraction.
    int cut = max_fraction - min_fraction;

    // Steps 11-12 are implemented by cut_trailing_zeroes.
    result.formatted_string = cut_trailing_zeroes(result.formatted_string, cut);

    // 13. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int, [[RoundingMagnitude]]: –f }.
    result.rounding_magnitude = -fraction;
    return result;
}

// 15.5.11 GetNumberFormatPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-getnumberformatpattern
// 1.1.14 GetNumberFormatPattern ( numberFormat, x ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-getnumberformatpattern
Optional<Variant<StringView, DeprecatedString>> get_number_format_pattern(VM& vm, NumberFormat& number_format, MathematicalValue const& number, ::Locale::NumberFormat& found_pattern)
{
    // 1. Let localeData be %NumberFormat%.[[LocaleData]].
    // 2. Let dataLocale be numberFormat.[[DataLocale]].
    // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
    // 4. Let patterns be dataLocaleData.[[patterns]].
    // 5. Assert: patterns is a Record (see 15.3.3).
    Optional<::Locale::NumberFormat> patterns;

    // 6. Let style be numberFormat.[[Style]].
    switch (number_format.style()) {
    // 7. If style is "percent", then
    case NumberFormat::Style::Percent:
        // a. Let patterns be patterns.[[percent]].
        patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Percent);
        break;

    // 8. Else if style is "unit", then
    case NumberFormat::Style::Unit: {
        // a. Let unit be numberFormat.[[Unit]].
        // b. Let unitDisplay be numberFormat.[[UnitDisplay]].
        // c. Let patterns be patterns.[[unit]].
        // d. If patterns doesn't have a field [[<unit>]], then
        //     i. Let unit be "fallback".
        // e. Let patterns be patterns.[[<unit>]].
        // f. Let patterns be patterns.[[<unitDisplay>]].
        auto formats = ::Locale::get_unit_formats(number_format.data_locale(), number_format.unit(), number_format.unit_display());
        auto plurality = resolve_plural(number_format, ::Locale::PluralForm::Cardinal, number.to_value(vm));

        if (auto it = formats.find_if([&](auto& p) { return p.plurality == plurality; }); it != formats.end())
            patterns = move(*it);

        break;
    }

    // 9. Else if style is "currency", then
    case NumberFormat::Style::Currency:
        // a. Let currency be numberFormat.[[Currency]].
        // b. Let currencyDisplay be numberFormat.[[CurrencyDisplay]].
        // c. Let currencySign be numberFormat.[[CurrencySign]].
        // d. Let patterns be patterns.[[currency]].
        // e. If patterns doesn't have a field [[<currency>]], then
        //     i. Let currency be "fallback".
        // f. Let patterns be patterns.[[<currency>]].
        // g. Let patterns be patterns.[[<currencyDisplay>]].
        // h. Let patterns be patterns.[[<currencySign>]].

        // Handling of other [[CurrencyDisplay]] options will occur after [[SignDisplay]].
        if (number_format.currency_display() == NumberFormat::CurrencyDisplay::Name) {
            auto formats = ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::CurrencyUnit);
            auto plurality = resolve_plural(number_format, ::Locale::PluralForm::Cardinal, number.to_value(vm));

            if (auto it = formats.find_if([&](auto& p) { return p.plurality == plurality; }); it != formats.end()) {
                patterns = move(*it);
                break;
            }
        }

        switch (number_format.currency_sign()) {
        case NumberFormat::CurrencySign::Standard:
            patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Currency);
            break;
        case NumberFormat::CurrencySign::Accounting:
            patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Accounting);
            break;
        }

        break;

    // 10. Else,
    case NumberFormat::Style::Decimal:
        // a. Assert: style is "decimal".
        // b. Let patterns be patterns.[[decimal]].
        patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Decimal);
        break;

    default:
        VERIFY_NOT_REACHED();
    }

    if (!patterns.has_value())
        return {};

    StringView pattern;

    // 11. Let signDisplay be numberFormat.[[SignDisplay]].
    switch (number_format.sign_display()) {
    // 12. If signDisplay is "never", then
    case NumberFormat::SignDisplay::Never:
        // a. Let pattern be patterns.[[zeroPattern]].
        pattern = patterns->zero_format;
        break;

    // 13. Else if signDisplay is "auto", then
    case NumberFormat::SignDisplay::Auto:
        // a. If x is 0 or x > 0 or x is NaN, then
        if (number.is_zero() || number.is_positive() || number.is_nan()) {
            // i. Let pattern be patterns.[[zeroPattern]].
            pattern = patterns->zero_format;
        }
        // b. Else,
        else {
            // i. Let pattern be patterns.[[negativePattern]].
            pattern = patterns->negative_format;
        }
        break;

    // 14. Else if signDisplay is "always", then
    case NumberFormat::SignDisplay::Always:
        // a. If x is 0 or x > 0 or x is NaN, then
        if (number.is_zero() || number.is_positive() || number.is_nan()) {
            // i. Let pattern be patterns.[[positivePattern]].
            pattern = patterns->positive_format;
        }
        // b. Else,
        else {
            // i. Let pattern be patterns.[[negativePattern]].
            pattern = patterns->negative_format;
        }
        break;

    // 15. Else if signDisplay is "exceptZero", then
    case NumberFormat::SignDisplay::ExceptZero:
        // a. If x is 0 or x is -0 or x is NaN, then
        if (number.is_zero() || number.is_negative_zero() || number.is_nan()) {
            // i. Let pattern be patterns.[[zeroPattern]].
            pattern = patterns->zero_format;
        }
        // b. Else if x > 0, then
        else if (number.is_positive()) {
            // i. Let pattern be patterns.[[positivePattern]].
            pattern = patterns->positive_format;
        }
        // c. Else,
        else {
            // i. Let pattern be patterns.[[negativePattern]].
            pattern = patterns->negative_format;
        }
        break;

    // 16. Else,
    case NumberFormat::SignDisplay::Negative:
        // a. Assert: signDisplay is "negative".
        // b. If x is 0 or x is -0 or x > 0 or x is NaN, then
        if (number.is_zero() || number.is_negative_zero() || number.is_positive() || number.is_nan()) {
            // i. Let pattern be patterns.[[zeroPattern]].
            pattern = patterns->zero_format;
        }
        // c. Else,
        else {
            // i. Let pattern be patterns.[[negativePattern]].
            pattern = patterns->negative_format;
        }
        break;

    default:
        VERIFY_NOT_REACHED();
    }

    found_pattern = patterns.release_value();

    // Handling of steps 9b/9g: Depending on the currency display and the format pattern found above,
    // we might need to mutate the format pattern to inject a space between the currency display and
    // the currency number.
    if (number_format.style() == NumberFormat::Style::Currency) {
        auto modified_pattern = ::Locale::augment_currency_format_pattern(number_format.resolve_currency_display(), pattern);
        if (modified_pattern.has_value())
            return modified_pattern.release_value();
    }

    // 16. Return pattern.
    return pattern;
}

// 15.5.12 GetNotationSubPattern ( numberFormat, exponent ), https://tc39.es/ecma402/#sec-getnotationsubpattern
Optional<StringView> get_notation_sub_pattern(NumberFormat& number_format, int exponent)
{
    // 1. Let localeData be %NumberFormat%.[[LocaleData]].
    // 2. Let dataLocale be numberFormat.[[DataLocale]].
    // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
    // 4. Let notationSubPatterns be dataLocaleData.[[notationSubPatterns]].
    // 5. Assert: notationSubPatterns is a Record (see 15.3.3).

    // 6. Let notation be numberFormat.[[Notation]].
    auto notation = number_format.notation();

    // 7. If notation is "scientific" or notation is "engineering", then
    if ((notation == NumberFormat::Notation::Scientific) || (notation == NumberFormat::Notation::Engineering)) {
        // a. Return notationSubPatterns.[[scientific]].
        auto notation_sub_patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Scientific);
        if (!notation_sub_patterns.has_value())
            return {};

        return notation_sub_patterns->zero_format;
    }
    // 8. Else if exponent is not 0, then
    else if (exponent != 0) {
        // a. Assert: notation is "compact".
        VERIFY(notation == NumberFormat::Notation::Compact);

        // b. Let compactDisplay be numberFormat.[[CompactDisplay]].
        // c. Let compactPatterns be notationSubPatterns.[[compact]].[[<compactDisplay>]].
        // d. Return compactPatterns.[[<exponent>]].
        if (number_format.has_compact_format())
            return number_format.compact_format().zero_format;
    }

    // 9. Else,
    //     a. Return "{number}".
    return "{number}"sv;
}

// 15.5.13 ComputeExponent ( numberFormat, x ), https://tc39.es/ecma402/#sec-computeexponent
int compute_exponent(NumberFormat& number_format, MathematicalValue number)
{
    // 1. If x = 0, then
    if (number.is_zero()) {
        // a. Return 0.
        return 0;
    }

    // 2. If x < 0, then
    if (number.is_negative()) {
        // a. Let x = -x.
        number.negate();
    }

    // 3. Let magnitude be the base 10 logarithm of x rounded down to the nearest integer.
    int magnitude = number.logarithmic_floor();

    // 4. Let exponent be ComputeExponentForMagnitude(numberFormat, magnitude).
    int exponent = compute_exponent_for_magnitude(number_format, magnitude);

    // 5. Let x be x × 10^(-exponent).
    number = number.multiplied_by_power(-exponent);

    // 6. Let formatNumberResult be FormatNumericToString(numberFormat, x).
    auto format_number_result = format_numeric_to_string(number_format, move(number));

    // 7. If formatNumberResult.[[RoundedNumber]] = 0, then
    if (format_number_result.rounded_number.is_zero()) {
        // a. Return exponent.
        return exponent;
    }

    // 8. Let newMagnitude be the base 10 logarithm of formatNumberResult.[[RoundedNumber]] rounded down to the nearest integer.
    int new_magnitude = format_number_result.rounded_number.logarithmic_floor();

    // 9. If newMagnitude is magnitude – exponent, then
    if (new_magnitude == magnitude - exponent) {
        // a. Return exponent.
        return exponent;
    }

    // 10. Return ComputeExponentForMagnitude(numberFormat, magnitude + 1).
    return compute_exponent_for_magnitude(number_format, magnitude + 1);
}

// 15.5.14 ComputeExponentForMagnitude ( numberFormat, magnitude ), https://tc39.es/ecma402/#sec-computeexponentformagnitude
int compute_exponent_for_magnitude(NumberFormat& number_format, int magnitude)
{
    // 1. Let notation be numberFormat.[[Notation]].
    switch (number_format.notation()) {
    // 2. If notation is "standard", then
    case NumberFormat::Notation::Standard:
        // a. Return 0.
        return 0;

    // 3. Else if notation is "scientific", then
    case NumberFormat::Notation::Scientific:
        // a. Return magnitude.
        return magnitude;

    // 4. Else if notation is "engineering", then
    case NumberFormat::Notation::Engineering: {
        // a. Let thousands be the greatest integer that is not greater than magnitude / 3.
        double thousands = floor(static_cast<double>(magnitude) / 3.0);

        // b. Return thousands × 3.
        return static_cast<int>(thousands) * 3;
    }

    // 5. Else,
    case NumberFormat::Notation::Compact: {
        // a. Assert: notation is "compact".
        VERIFY(number_format.has_compact_display());

        // b. Let exponent be an implementation- and locale-dependent (ILD) integer by which to scale a number of the given magnitude in compact notation for the current locale.
        // c. Return exponent.
        Vector<::Locale::NumberFormat> format_rules;

        if (number_format.style() == NumberFormat::Style::Currency)
            format_rules = ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::CurrencyShort);
        else if (number_format.compact_display() == NumberFormat::CompactDisplay::Long)
            format_rules = ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::DecimalLong);
        else
            format_rules = ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::DecimalShort);

        ::Locale::NumberFormat const* best_number_format = nullptr;

        for (auto const& format_rule : format_rules) {
            if (format_rule.magnitude > magnitude)
                break;
            best_number_format = &format_rule;
        }

        if (best_number_format == nullptr)
            return 0;

        number_format.set_compact_format(*best_number_format);
        return best_number_format->exponent;
    }

    default:
        VERIFY_NOT_REACHED();
    }
}

// 1.1.18 ToIntlMathematicalValue ( value ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-tointlmathematicalvalue
ThrowCompletionOr<MathematicalValue> to_intl_mathematical_value(VM& vm, Value value)
{

    // 1. Let primValue be ? ToPrimitive(value, number).
    auto primitive_value = TRY(value.to_primitive(vm, Value::PreferredType::Number));

    // 2. If Type(primValue) is BigInt, return the mathematical value of primValue.
    if (primitive_value.is_bigint())
        return primitive_value.as_bigint().big_integer();

    // FIXME: The remaining steps are being refactored into a new Runtime Semantic, StringIntlMV.
    //        We short-circuit some of these steps to avoid known pitfalls.
    //        See: https://github.com/tc39/proposal-intl-numberformat-v3/pull/82
    if (!primitive_value.is_string()) {
        auto number = TRY(primitive_value.to_number(vm));
        return number.as_double();
    }

    // 3. If Type(primValue) is String,
    // a.     Let str be primValue.
    auto const& string = primitive_value.as_string().deprecated_string();

    // Step 4 handled separately by the FIXME above.

    // 5. If the grammar cannot interpret str as an expansion of StringNumericLiteral, return not-a-number.
    // 6. Let mv be the MV, a mathematical value, of ? ToNumber(str), as described in 7.1.4.1.1.
    auto mathematical_value = TRY(primitive_value.to_number(vm)).as_double();

    // 7. If mv is 0 and the first non white space code point in str is -, return negative-zero.
    if (mathematical_value == 0.0 && string.view().trim_whitespace(TrimMode::Left).starts_with('-'))
        return MathematicalValue::Symbol::NegativeZero;

    // 8. If mv is 10^10000 and str contains Infinity, return positive-infinity.
    if (mathematical_value == pow(10, 10000) && string.contains("Infinity"sv))
        return MathematicalValue::Symbol::PositiveInfinity;

    // 9. If mv is -10^10000 and str contains Infinity, return negative-infinity.
    if (mathematical_value == pow(-10, 10000) && string.contains("Infinity"sv))
        return MathematicalValue::Symbol::NegativeInfinity;

    // 10. Return mv.
    return mathematical_value;
}

// 1.1.19 GetUnsignedRoundingMode ( roundingMode, isNegative ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-getunsignedroundingmode
NumberFormat::UnsignedRoundingMode get_unsigned_rounding_mode(NumberFormat::RoundingMode rounding_mode, bool is_negative)
{
    // 1. If isNegative is true, return the specification type in the third column of Table 2 where the first column is roundingMode and the second column is "negative".
    // 2. Else, return the specification type in the third column of Table 2 where the first column is roundingMode and the second column is "positive".

    // Table 2: Conversion from rounding mode to unsigned rounding mode, https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#table-intl-unsigned-rounding-modes
    switch (rounding_mode) {
    case NumberFormat::RoundingMode::Ceil:
        return is_negative ? NumberFormat::UnsignedRoundingMode::Zero : NumberFormat::UnsignedRoundingMode::Infinity;
    case NumberFormat::RoundingMode::Floor:
        return is_negative ? NumberFormat::UnsignedRoundingMode::Infinity : NumberFormat::UnsignedRoundingMode::Zero;
    case NumberFormat::RoundingMode::Expand:
        return NumberFormat::UnsignedRoundingMode::Infinity;
    case NumberFormat::RoundingMode::Trunc:
        return NumberFormat::UnsignedRoundingMode::Zero;
    case NumberFormat::RoundingMode::HalfCeil:
        return is_negative ? NumberFormat::UnsignedRoundingMode::HalfZero : NumberFormat::UnsignedRoundingMode::HalfInfinity;
    case NumberFormat::RoundingMode::HalfFloor:
        return is_negative ? NumberFormat::UnsignedRoundingMode::HalfInfinity : NumberFormat::UnsignedRoundingMode::HalfZero;
    case NumberFormat::RoundingMode::HalfExpand:
        return NumberFormat::UnsignedRoundingMode::HalfInfinity;
    case NumberFormat::RoundingMode::HalfTrunc:
        return NumberFormat::UnsignedRoundingMode::HalfZero;
    case NumberFormat::RoundingMode::HalfEven:
        return NumberFormat::UnsignedRoundingMode::HalfEven;
    default:
        VERIFY_NOT_REACHED();
    };
}

// 1.1.20 ApplyUnsignedRoundingMode ( x, r1, r2, unsignedRoundingMode ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-applyunsignedroundingmode
RoundingDecision apply_unsigned_rounding_mode(MathematicalValue const& x, MathematicalValue const& r1, MathematicalValue const& r2, Optional<NumberFormat::UnsignedRoundingMode> const& unsigned_rounding_mode)
{
    // 1. If x is equal to r1, return r1.
    if (x.is_equal_to(r1))
        return RoundingDecision::LowerValue;

    // FIXME: We skip this assertion due floating point inaccuracies. For example, entering "1.2345"
    //        in the JS REPL results in "1.234499999999999", and may cause this assertion to fail.
    //
    //        This should be resolved when the "Intl mathematical value" is implemented to support
    //        arbitrarily precise decimals.
    //        https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#intl-mathematical-value
    // 2. Assert: r1 < x < r2.

    // 3. Assert: unsignedRoundingMode is not undefined.
    VERIFY(unsigned_rounding_mode.has_value());

    // 4. If unsignedRoundingMode is zero, return r1.
    if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::Zero)
        return RoundingDecision::LowerValue;

    // 5. If unsignedRoundingMode is infinity, return r2.
    if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::Infinity)
        return RoundingDecision::HigherValue;

    // 6. Let d1 be x – r1.
    auto d1 = x.minus(r1);

    // 7. Let d2 be r2 – x.
    auto d2 = r2.minus(x);

    // 8. If d1 < d2, return r1.
    if (d1.is_less_than(d2))
        return RoundingDecision::LowerValue;

    // 9. If d2 < d1, return r2.
    if (d2.is_less_than(d1))
        return RoundingDecision::HigherValue;

    // 10. Assert: d1 is equal to d2.
    VERIFY(d1.is_equal_to(d2));

    // 11. If unsignedRoundingMode is half-zero, return r1.
    if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::HalfZero)
        return RoundingDecision::LowerValue;

    // 12. If unsignedRoundingMode is half-infinity, return r2.
    if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::HalfInfinity)
        return RoundingDecision::HigherValue;

    // 13. Assert: unsignedRoundingMode is half-even.
    VERIFY(unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::HalfEven);

    // 14. Let cardinality be (r1 / (r2 – r1)) modulo 2.
    auto cardinality = r1.divided_by(r2.minus(r1));

    // 15. If cardinality is 0, return r1.
    if (cardinality.modulo_is_zero(2))
        return RoundingDecision::LowerValue;

    // 16. Return r2.
    return RoundingDecision::HigherValue;
}

// 1.1.21 PartitionNumberRangePattern ( numberFormat, x, y ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-partitionnumberrangepattern
ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_number_range_pattern(VM& vm, NumberFormat& number_format, MathematicalValue start, MathematicalValue end)
{
    // 1. If x is NaN or y is NaN, throw a RangeError exception.
    if (start.is_nan())
        return vm.throw_completion<RangeError>(ErrorType::IntlNumberIsNaN, "start"sv);
    if (end.is_nan())
        return vm.throw_completion<RangeError>(ErrorType::IntlNumberIsNaN, "end"sv);

    // 2. Let result be a new empty List.
    Vector<PatternPartitionWithSource> result;

    // 3. Let xResult be ? PartitionNumberPattern(numberFormat, x).
    auto raw_start_result = partition_number_pattern(vm, number_format, move(start));
    auto start_result = PatternPartitionWithSource::create_from_parent_list(move(raw_start_result));

    // 4. Let yResult be ? PartitionNumberPattern(numberFormat, y).
    auto raw_end_result = partition_number_pattern(vm, number_format, move(end));
    auto end_result = PatternPartitionWithSource::create_from_parent_list(move(raw_end_result));

    // 5. If xResult is equal to yResult, return FormatApproximately(numberFormat, xResult).
    if (start_result == end_result)
        return format_approximately(number_format, move(start_result));

    // 6. For each r in xResult, do
    for (auto& part : start_result) {
        // i. Set r.[[Source]] to "startRange".
        part.source = "startRange"sv;
    }

    // 7. Add all elements in xResult to result in order.
    result = move(start_result);

    // 8. Let rangeSeparator be an ILND String value used to separate two numbers.
    auto range_separator_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::RangeSeparator).value_or("-"sv);
    auto range_separator = ::Locale::augment_range_pattern(range_separator_symbol, result.last().value, end_result[0].value);

    // 9. Append a new Record { [[Type]]: "literal", [[Value]]: rangeSeparator, [[Source]]: "shared" } element to result.
    PatternPartitionWithSource part;
    part.type = "literal"sv;
    part.value = range_separator.value_or(range_separator_symbol);
    part.source = "shared"sv;
    result.append(move(part));

    // 10. For each r in yResult, do
    for (auto& part : end_result) {
        // a. Set r.[[Source]] to "endRange".
        part.source = "endRange"sv;
    }

    // 11. Add all elements in yResult to result in order.
    result.extend(move(end_result));

    // 12. Return ! CollapseNumberRange(result).
    return collapse_number_range(move(result));
}

// 1.1.22 FormatApproximately ( numberFormat, result ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-formatapproximately
Vector<PatternPartitionWithSource> format_approximately(NumberFormat& number_format, Vector<PatternPartitionWithSource> result)
{
    // 1. Let i be an index into result, determined by an implementation-defined algorithm based on numberFormat and result.
    // 2. Let approximatelySign be an ILND String value used to signify that a number is approximate.
    auto approximately_sign = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::ApproximatelySign).value_or("~"sv);

    // 3. Insert a new Record { [[Type]]: "approximatelySign", [[Value]]: approximatelySign } at index i in result.
    PatternPartitionWithSource partition;
    partition.type = "approximatelySign"sv;
    partition.value = approximately_sign;

    result.insert_before_matching(move(partition), [](auto const& part) {
        return part.type.is_one_of("integer"sv, "decimal"sv, "plusSign"sv, "minusSign"sv, "percentSign"sv, "currency"sv);
    });

    // 4. Return result.
    return result;
}

// 1.1.23 CollapseNumberRange ( result ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-collapsenumberrange
Vector<PatternPartitionWithSource> collapse_number_range(Vector<PatternPartitionWithSource> result)
{
    // Returning result unmodified is guaranteed to be a correct implementation of CollapseNumberRange.
    return result;
}

// 1.1.24 FormatNumericRange( numberFormat, x, y ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-formatnumericrange
ThrowCompletionOr<DeprecatedString> format_numeric_range(VM& vm, NumberFormat& number_format, MathematicalValue start, MathematicalValue end)
{
    // 1. Let parts be ? PartitionNumberRangePattern(numberFormat, x, y).
    auto parts = TRY(partition_number_range_pattern(vm, number_format, move(start), move(end)));

    // 2. Let result be the empty String.
    StringBuilder result;

    // 3. For each part in parts, do
    for (auto& part : parts) {
        // a. Set result to the string-concatenation of result and part.[[Value]].
        result.append(move(part.value));
    }

    // 4. Return result.
    return result.build();
}

// 1.1.25 FormatNumericRangeToParts( numberFormat, x, y ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-formatnumericrangetoparts
ThrowCompletionOr<Array*> format_numeric_range_to_parts(VM& vm, NumberFormat& number_format, MathematicalValue start, MathematicalValue end)
{
    auto& realm = *vm.current_realm();

    // 1. Let parts be ? PartitionNumberRangePattern(numberFormat, x, y).
    auto parts = TRY(partition_number_range_pattern(vm, number_format, move(start), move(end)));

    // 2. Let result be ! ArrayCreate(0).
    auto result = MUST(Array::create(realm, 0));

    // 3. Let n be 0.
    size_t n = 0;

    // 4. For each Record { [[Type]], [[Value]] } part in parts, do
    for (auto& part : parts) {
        // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
        auto* object = Object::create(realm, realm.intrinsics().object_prototype());

        // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
        MUST(object->create_data_property_or_throw(vm.names.type, PrimitiveString::create(vm, part.type)));

        // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
        MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(vm, move(part.value))));

        // d. Perform ! CreateDataPropertyOrThrow(O, "source", part.[[Source]]).
        MUST(object->create_data_property_or_throw(vm.names.source, PrimitiveString::create(vm, part.source)));

        // e. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
        MUST(result->create_data_property_or_throw(n, object));

        // f. Increment n by 1.
        ++n;
    }

    // 5. Return result.
    return result.ptr();
}

}