fin_decimal 0.4.0

A high-performance decimal fixed-point arithmetic library for financial applications
Documentation
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
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
//!
//! A Fixed-point decimal implementation written in Rust suitable
//! for a wide range of financial calculations that require significant
//! integral and fractional digits to follow decimal arithmetic rounding.
//!
//! The binary representation consists of a 64 bit integer number,
//! multiplied by power of 10 - default 10000 for 'Amount64' type.
//!
//! Such implementation results in highly efficient addition and subtraction
//! which are implemented as native operations on i64. These operations also
//! don't result in any rounding errors.
//!
//! Multiplication and division are also relatively efficient and implemented
//! via operations on i128 type internally. On some platforms (like x86-64) where
//! 64 x 64 bit multiplication with 128 bit result and division of 128 bit integer
//! by 64 bit are implemented as native instructions, performance penalty compared
//! to regular i64 division and multiplication is negligible.
//!
//! While 4 fractional decimal digits handles most of cases for accounting and tax
//! computations, in some cases like exchange rates higher precision is desirable.
//! To address this, a sibling type 'Rate' is introduced with 8 fractional digits.
//!
//! ## Wider backings: 128-bit and 256-bit
//!
//! When the ~±922 trillion range of `Amount64` is not enough, the same decimal
//! semantics are available on wider backing integers:
//!
//! * [`Amount128`] / [`Rate128`] ([`Decimal128`]): backed by `i128`, range about
//!   ±1.7 * 10^34 at 4 digits.
//! * [`Amount256`] / [`Rate256`] ([`Decimal256`]): backed by a 256-bit integer
//!   ([`I256`]), range about ±5.8 * 10^72 at 4 digits.
//!
//! Addition and subtraction remain native integer operations (one or two
//! add/adc instructions). Multiplication builds the double-width intermediate
//! from 64-bit limbs and re-scales it by the compile-time constant 10^DIGITS
//! using Möller–Granlund reciprocal multiplication with a compile-time
//! reciprocal — no division instructions and no compiler builtins on that
//! path, on any architecture (`scripts/check_asm.sh` verifies the generated
//! code). Division by another decimal (a runtime divisor) uses a
//! 128-bit-by-64-bit division primitive — the native `div` instruction on
//! `x86_64` with the `asm` feature, or a portable long division on 32-bit
//! half-digits — and Knuth's algorithm D over the significant limbs for
//! divisors wider than one limb.
//!
//! Key operations (`checked_mul`, `mul_rounded`, `round_to`, `trunc`, `powi`,
//! `from_str_rounded`, `from_str_const`, ...) are `const fn`, so rates, fees
//! and whole derived constants can be evaluated at compile time:
//!
//! ```rust
//! use fin_decimal::{Amount64, Rounding};
//! const PRICE: Amount64 = Amount64::from_str_const("19.99");
//! const RATE: Amount64 = Amount64::from_str_const("0.0825");
//! const TAX: Amount64 = PRICE.mul_rounded(RATE, Rounding::HalfEven);
//! ```
//!
//! The `*` and `/` operators of every backing panic on overflow regardless of
//! build profile (they share one arithmetic core); use
//! `checked_mul`/`checked_div` to get `None` instead.
//!
//! ## Usage
//!
//! The stable version of rust requires you to create a Decimal number
//! using one of its convenience methods.
//!
//! ```rust
//! use fin_decimal::Amount64;
//! use core::str::FromStr;
//!
//! // Using an integer number.
//! let from_int = Amount64::from(3); // 3.0000
//!
//! // Using a floating point number.
//! let from_f64 = Amount64::from(2.02f64); // 2.0200
//!
//! // From a string representation
//! let from_string = Amount64::from_str("2.02").unwrap(); // 2.0200
//!
//! // Using the `Into` trait
//! let my_int : Amount64 = 3i32.into();
//! ```
//!

//#![cfg_attr(feature = "no_std", no_std)]
//#![cfg_attr(feature = "asm", feature(llvm_asm))]
#![crate_name = "fin_decimal"]
#![crate_type = "lib"]
#![no_std]
#![deny(unconditional_recursion)]
#![warn(missing_docs)]
#![warn(clippy::all)]
//#![feature(llvm_asm)]
//#![feature(maybe_uninit_slice)]
//#![feature(const_fn)]
//#![feature(const_fn_union)]
//#![feature(rustc_attrs)]
//#![feature(half_open_range_patterns)]
//#![feature(exclusive_range_pattern)]
//#![feature(const_fn_floating_point_arithmetic)]
//#![feature(asm)]

use core::cmp::*;
use core::default::*;
use core::f64;
use core::fmt::*;
use core::hash::Hash;
use core::marker::*;
use core::ops::*;
use core::option::Option;
use core::result::Result;

use core::*;

mod common;
mod decimal128;
mod decimal256;
mod limbs;

pub use decimal128::{Amount128, Decimal128, Rate128};
pub use decimal256::{Amount256, Decimal256, I256, Rate256};

/// Not public API: internals re-exported only so the dependency-free bench
/// harness (`benches/perf.rs`) can compare the square-root cores against
/// each other. No stability guarantees whatsoever.
#[doc(hidden)]
pub mod bench_internals {
    pub use crate::limbs::{isqrt_f64, isqrt_newton};
}

/// Enum to store the various types of errors that can cause parsing an integer to fail.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AmountErrorKind {
    /// Value being parsed doesn't have any digits (could have sign and point though)
    ///
    /// Among other causes, this variant will be constructed when parsing an empty string.
    Empty,
    /// Contains an invalid digit.
    ///
    /// Among other causes, this variant will be constructed when parsing a string that
    /// contains a letter.
    InvalidDigit,
    /// Value is too large to store in target integer type.
    Overflow,
    /// Value cannot be represented exactly at the target decimal scale.
    ///
    /// Constructed when a value has more fractional digits than the target type
    /// can hold, so converting it would silently drop precision (e.g. building a
    /// 4-digit `Amount64` from `(mantissa: 1, exponent: -5)`).
    Inexact,
}

impl AmountErrorKind {
    /// Returns the kind of the error.
    pub fn kind(&self) -> &AmountErrorKind {
        self
    }
    #[doc(hidden)]
    pub fn __description(&self) -> &str {
        match self {
            AmountErrorKind::Empty => "cannot parse integer from empty string",
            AmountErrorKind::InvalidDigit => "invalid symbol found in string",
            AmountErrorKind::Overflow => "number too large to fit in target type",
            AmountErrorKind::Inexact => "value cannot be represented exactly at the target scale",
        }
    }
}

impl fmt::Display for AmountErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        core::fmt::Display::fmt(&self.__description(), f)
    }
}

/// Splits an i64 into a sign and a one-limb magnitude for the shared
/// sign-magnitude cores in [`limbs`].
#[inline]
const fn i64_sign_mag(v: i64) -> (bool, [u64; 1]) {
    (v < 0, [v.unsigned_abs()])
}

/// Rebuilds an i64 from a sign and a one-limb magnitude with the top bit
/// clear (guaranteed by the shared cores' symmetric-range check).
#[inline]
const fn i64_from_sign_mag(neg: bool, mag: [u64; 1]) -> i64 {
    let v = mag[0] as i64;
    if neg { v.wrapping_neg() } else { v }
}

#[inline]
// Compute pow of 10 for values 0..18 (which fits in i64 range)
// Returns 1 if pow is negative and 0 if result will overflow.
// Shares `limbs::upow10`'s power-of-ten table for the in-range lookup.
const fn ipow10(pow: i64) -> i64 {
    match (pow <= 0, pow >= 19) {
        (true, _) => 1,
        (_, true) => 0, // 10^19 overflows i64 (max ≈ 9.22e18)
        (_, _) => limbs::upow10(pow as u32) as i64,
    }
}

#[inline]
// Compute 10^pow as i128 for non-negative `pow`.
// Returns `None` if `pow` is negative or the result overflows i128.
const fn ipow10_i128(pow: i64) -> Option<i128> {
    if pow < 0 || pow > 38 {
        // 10^39 overflows i128.
        return None;
    }
    // Low powers (10^0..10^19) fit in u64, so reuse the shared `upow10` table
    // instead of duplicating those twenty values here at i128 width.
    if pow <= 19 {
        return Some(limbs::upow10(pow as u32) as i128);
    }
    // 10^20..10^38: extend the largest u64 power with a few multiplies. Only
    // extreme exponents reach here, so a short loop is cheaper than carrying a
    // 304-byte i128 table.
    let mut v = limbs::upow10(19) as i128; // 10^19
    let mut i = 19;
    while i < pow {
        v *= 10;
        i += 1;
    }
    Some(v)
}

#[test]
fn test_ipow10() {
    assert_eq!(ipow10(0), 1);
    assert_eq!(ipow10(-1), 1);
    assert_eq!(ipow10(19), 0); // check overflow

    assert_eq!(ipow10(1), 10);
    assert_eq!(ipow10(4), 10000);

    let mut p: i64 = 1;
    for x in 0..18i64 {
        assert_eq!(ipow10(x), p);
        p *= 10;
    }
}

#[test]
fn test_ipow10_i128() {
    // Negative powers are rejected.
    assert_eq!(ipow10_i128(-1), None);
    // In-range powers match a from-scratch multiply, up to the last that fits.
    let mut p: i128 = 1;
    for x in 0..=38i64 {
        assert_eq!(ipow10_i128(x), Some(p));
        if x < 38 {
            p *= 10;
        }
    }
    // 10^39 overflows i128: the boundary that drives Overflow/Inexact.
    assert_eq!(ipow10_i128(39), None);
    assert_eq!(ipow10_i128(1000), None);
}
/// Defines how to display the sign of the parsed number.
pub enum AmountSign {
    /// Omit the sign entirely.
    None,
    /// Display only the negative sign.
    Negative,
    /// Always display the sign (+ or -).
    Always,
}

/// Converts an i64 to a fixed-point string representation, optionally padded.
///
/// Thin wrapper over the shared limb formatter: same trailing-zero trimming
/// and half-away-from-zero precision rounding, no `unsafe`.
pub fn str_i64(
    num: i64,
    frac_digit: usize,
    precision: Option<usize>,
    sign: AmountSign,
    buf: &mut [u8],
) -> Option<&str> {
    limbs::str_mag(
        &[num.unsigned_abs()],
        num < 0,
        frac_digit,
        precision,
        sign,
        buf,
    )
}

#[test]
fn test_istr() {
    let mut buf = [0u8; 3 * mem::size_of::<i64>()];

    assert_eq!(
        str_i64(10000, 4, None, AmountSign::Negative, &mut buf),
        Some("1")
    );
    assert_eq!(
        str_i64(10001, 4, None, AmountSign::Negative, &mut buf),
        Some("1.0001")
    );
    assert_eq!(
        str_i64(10010, 4, None, AmountSign::Negative, &mut buf),
        Some("1.001")
    );
    assert_eq!(
        str_i64(10100, 4, None, AmountSign::Negative, &mut buf),
        Some("1.01")
    );
    assert_eq!(
        str_i64(11000, 4, None, AmountSign::Negative, &mut buf),
        Some("1.1")
    );
    assert_eq!(
        str_i64(101000000, 8, None, AmountSign::Negative, &mut buf),
        Some("1.01")
    );

    assert_eq!(
        str_i64(10000, 4, Some(4), AmountSign::Negative, &mut buf),
        Some("1.0000")
    );

    assert_eq!(
        str_i64(10000, 4, Some(5), AmountSign::Negative, &mut buf),
        Some("1.00000")
    );

    assert_eq!(
        str_i64(10001, 4, Some(5), AmountSign::Negative, &mut buf),
        Some("1.00010")
    );

    assert_eq!(
        str_i64(10000, 4, Some(3), AmountSign::Negative, &mut buf),
        Some("1.000")
    );
    assert_eq!(
        str_i64(10000, 4, Some(2), AmountSign::Negative, &mut buf),
        Some("1.00")
    );
    assert_eq!(
        str_i64(10100, 4, Some(2), AmountSign::Negative, &mut buf),
        Some("1.01")
    );
    assert_eq!(
        str_i64(10050, 4, Some(2), AmountSign::Negative, &mut buf),
        Some("1.01")
    );
    assert_eq!(
        str_i64(10050, 4, Some(1), AmountSign::Negative, &mut buf),
        Some("1.0")
    );
    assert_eq!(
        str_i64(-10050, 4, Some(1), AmountSign::Negative, &mut buf),
        Some("-1.0")
    );
    assert_eq!(
        str_i64(-10050, 4, Some(1), AmountSign::None, &mut buf),
        Some("1.0")
    );
    assert_eq!(
        str_i64(-10050, 4, Some(1), AmountSign::Always, &mut buf),
        Some("-1.0")
    );
    assert_eq!(
        str_i64(10050, 4, Some(1), AmountSign::Always, &mut buf),
        Some("+1.0")
    );

    let mut small_buf = [0u8; 5];
    assert_eq!(
        str_i64(10050, 4, Some(3), AmountSign::Negative, &mut small_buf),
        Some("1.005")
    );
    assert_eq!(
        str_i64(10050, 4, Some(4), AmountSign::Negative, &mut small_buf),
        None
    );
    assert_eq!(
        str_i64(100500, 4, Some(3), AmountSign::Negative, &mut small_buf),
        None
    );
}

/// Converts a string in base 10 to a fixed-point scaled value.
/// Can be used with non-default scale to handle higher precision
/// exchange rates and other scenarios with longer fractional parts.
///
/// Fractional digits beyond `scale` are dropped with `Rounding::HalfUp`. Use
/// [`parse_decimal_i64_rounded`] to choose a different rounding mode.
pub fn parse_decimal_i64(src: &str, scale: u8) -> Result<i64, AmountErrorKind> {
    parse_decimal_i64_rounded(src, scale, Rounding::HalfUp)
}

/// Converts a string in base 10 to a fixed-point scaled value, rounding any
/// fractional digits beyond `scale` with the given [`Rounding`] mode.
///
/// Inputs that carry more precision than `scale` can hold are accepted (never an
/// error) and rounded; trailing zeros are dropped exactly. The rounding is
/// "correct" in the IEEE sense: it inspects the first dropped digit together with
/// a sticky flag (whether any further digit is non-zero) and, for `HalfEven`, the
/// parity of the retained value.
pub const fn parse_decimal_i64_rounded(
    src: &str,
    scale: u8,
    mode: Rounding,
) -> Result<i64, AmountErrorKind> {
    // Delegates to the shared limb parser at one-limb width; only the
    // symmetric i64 range check lives here.
    let (neg, mag) = match limbs::parse_decimal_mag_rounded::<1>(src, scale, mode) {
        Ok(v) => v,
        Err(e) => return Err(e),
    };
    if mag[0] > i64::MAX as u64 {
        return Err(AmountErrorKind::Overflow);
    }
    Ok(i64_from_sign_mag(neg, mag))
}

/// `Rounding` represents the different strategies that can be used.
///
/// `Rounding::HalfEven` - Rounds toward the nearest even number, e.g. 5.5 -> 6, 4.5 -> 4
/// `Rounding::HalfUp` - Rounds up if the value >= 5, otherwise rounds down, e.g. 6.5 -> 7 (default),
/// `Rounding::HalfDown` - Rounds down if the value =< 5, otherwise rounds up, e.g.
/// 4.5 -> 4, 4.51 -> 5,  1.4999 -> 1
/// `Rounding::Down` - Always round down.
/// `Rounding::Up` - Always round up.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rounding {
    /// Rounds toward the nearest even number, e.g. 5.5 -> 6, 4.5 -> 4
    HalfEven,
    /// Rounds up if the value >= 5, otherwise rounds down, e.g. 6.5 -> 7 (default)
    HalfUp,
    /// Rounds down if the value <= 5, otherwise rounds up, e.g. 4.5 -> 4, 4.51 -> 5
    HalfDown,
    /// Always rounds down.
    Down,
    /// Always rounds up.
    Up,
}

/// An exact even split of an amount into `n` parts, as produced by
/// `split_evenly` on each decimal type: `high_count` parts of `high` plus
/// `low_count` parts of `low`.
///
/// Invariants: `high_count + low_count == n`,
/// `high * high_count + low * low_count == total` **exactly** (no value is
/// ever created or lost — the penny-conservation property), and when the
/// split is inexact `high` exceeds `low` by exactly one unit in the last
/// place, away from zero. When the split is exact, `high == low` and
/// `high_count == 0`.
///
/// For a negative total the parts are negative and `high` is the part with
/// the larger magnitude (the more negative one).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EvenSplit<T> {
    /// The larger-magnitude part (one ulp beyond `low`, away from zero).
    pub high: T,
    /// How many of the `n` parts are `high`.
    pub high_count: u32,
    /// The smaller-magnitude part (the total over `n`, toward zero).
    pub low: T,
    /// How many of the `n` parts are `low`.
    pub low_count: u32,
}

/// Amount64 type implements decimal fixed-point arithmetic for financial computations.
/// It is implemented to be as efficient as possible with most common add/sub operations
/// to be native binary add/sub.
/// Actual decimal processing is needed for multiplication and division where rounding
/// should follow specific rules.
/// Number of decimal points is chosen to be 4 - this seems to be enough for most use cases
/// except for exchange rates where sometimes up to 8 decimal digits is required
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Decimal<const DIGITS: u8>(pub i64);

/// Amount64 is a 64-bit integer based decimal type with 4 decimal digits precision.
pub type Amount64 = Decimal<4>;
/// Rate64 is a 64-bit integer based decimal type with 8 decimal digits precision.
pub type Rate64 = Decimal<8>;

impl<const DIGITS: u8> Decimal<DIGITS> {
    /// The decimal scale: the number of fractional digits.
    ///
    /// A stable name for the scale that is independent of the const-generic
    /// `DIGITS` parameter. It survives the eventual move off the const-generic
    /// form (when `Decimal` becomes a trait or a wider concrete type, `DIGITS`
    /// disappears but `SCALE` stays).
    pub const SCALE: i32 = DIGITS as i32;

    /// The multiplier used to scale values up. Equal to 10^DIGITS.
    pub const SCALE_INT: i64 = ipow10(DIGITS as i64);

    /// The largest value that can be represented by this type.
    pub const MAX: Self = Decimal::<DIGITS>(i64::MAX);
    /// The smallest value that can be represented by this type.
    pub const MIN: Self = Decimal::<DIGITS>(-i64::MAX); // make MIN symmetric

    /// Constant equal to '1'
    pub const ONE: Self = Decimal::<DIGITS>(Self::SCALE_INT);
    /// Constant equal to '-1'
    pub const MINUS_ONE: Self = Decimal::<DIGITS>(-Self::SCALE_INT);
    /// Constant equal to '0'
    pub const ZERO: Self = Decimal::<DIGITS>(0);

    /// The smallest integer value that can be represented by this type.
    pub const INT_MIN: i64 = (i64::MIN + 1) / Self::SCALE_INT;
    /// The largest integer value that can be represented by this type.
    pub const INT_MAX: i64 = i64::MAX / Self::SCALE_INT;

    /// The smallest f64 value that can be represented.
    pub const F64_MIN: f64 = (i64::MIN + 1) as f64 / Self::SCALE_INT as f64; // -922337203685477.5807f64;
    /// The largest f64 value that can be represented.
    pub const F64_MAX: f64 = i64::MAX as f64 / Self::SCALE_INT as f64; //922337203685477.5807f64;

    /// Half of the scaling factor, used for rounding.
    pub const SCALE_INT_HALF: i64 = Self::SCALE_INT / 2;

    /// The multiplier used to scale values up, as f64.
    pub const SCALE_F64: f64 = Self::SCALE_INT as f64;

    /// Scale factor for 1/100 of unit.
    #[deprecated(
        since = "0.3.3",
        note = "only served the old round100 implementation (and is 0 for DIGITS < 2); use round_dp"
    )]
    pub const SCALE_INT_100: i64 = Self::SCALE_INT / 100;
    /// Half of scale factor for 1/100 of unit.
    #[deprecated(
        since = "0.3.3",
        note = "only served the old round100 implementation (and is 0 for DIGITS < 3); use round_dp"
    )]
    #[allow(deprecated)]
    pub const SCALE_INT_HALF_100: i64 = Self::SCALE_INT_100 / 2;

    /// Constructs a new decimal integer with value 0.
    ///
    /// # Examples
    /// ```rust
    /// use fin_decimal::Amount64;
    /// let i = Amount64::new();
    /// ```
    #[inline]
    pub fn new() -> Self {
        Decimal::<DIGITS>(0)
    }

    /// Tries to convert a f32 to a Decimal.
    #[inline]
    pub fn from_f32(val: f32) -> Result<Self, AmountErrorKind> {
        Self::from_f64(val as f64)
    }

    /// Tries to convert a f64 to a Decimal.
    #[inline]
    pub fn from_f64(val: f64) -> Result<Self, AmountErrorKind> {
        if (Self::F64_MIN..=Self::F64_MAX).contains(&val) {
            Ok(Decimal::<DIGITS>((val * Self::SCALE_F64) as i64))
        } else {
            Err(AmountErrorKind::Overflow)
        }
    }

    /// Tries to convert an i64 to a Decimal.
    #[inline]
    pub const fn from_i64(val: i64) -> Result<Self, AmountErrorKind> {
        if (val <= Self::INT_MAX) && (val >= Self::INT_MIN) {
            Ok(Decimal::<DIGITS>(val * Self::SCALE_INT))
        } else {
            Err(AmountErrorKind::Overflow)
        }
    }

    /// Converts the Decimal back into an f64.
    #[inline]
    pub fn to_f64(self) -> f64 {
        // use division as 0.0001 doesn't have exact representation in f64
        self.0 as f64 / Self::SCALE_F64
    }

    /// Converts the Decimal back into an i64 (truncating the fractional part).
    #[inline]
    pub const fn to_i64(self) -> i64 {
        self.0 / Self::SCALE_INT
    }

    /// Returns the raw backing value widened to `i128`.
    ///
    /// This is the unscaled mantissa: the stored integer such that the value
    /// equals `mantissa * 10^(-SCALE)`. The return type is deliberately `i128`,
    /// not the current `i64` backing, so this signature stays stable when the
    /// backing integer widens (`i64` → `i128` → …).
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::Amount64;
    /// let a = Amount64::from(3); // SCALE = 4
    /// assert_eq!(a.mantissa(), 30000);
    /// ```
    #[inline]
    pub const fn mantissa(self) -> i128 {
        self.0 as i128
    }

    /// Decomposes the value into `(mantissa, exponent)` such that the value
    /// equals `mantissa * 10^exponent`.
    ///
    /// The exponent is always `-SCALE`. This is the symmetric counterpart of
    /// [`from_decimal_parts`](Self::from_decimal_parts) and lets serialization
    /// codecs encode without reaching into the backing field directly.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::Amount64;
    /// let a = Amount64::from(3); // SCALE = 4
    /// assert_eq!(a.to_decimal_parts(), (30000, -4));
    /// ```
    #[inline]
    pub const fn to_decimal_parts(self) -> (i128, i32) {
        (self.0 as i128, -Self::SCALE)
    }

    /// Builds a value from `(mantissa, exponent)`, where the represented number
    /// is `mantissa * 10^exponent`.
    ///
    /// The value is rescaled to this type's fixed [`SCALE`](Self::SCALE):
    /// * If it needs to be scaled up (more fractional capacity than the input),
    ///   the mantissa is multiplied by the appropriate power of ten; an
    ///   [`Overflow`](AmountErrorKind::Overflow) is returned if the result does
    ///   not fit the backing integer.
    /// * If it needs to be scaled down (the input carries more fractional digits
    ///   than this type can hold), the conversion is **exact-or-error**: it
    ///   succeeds only when the dropped digits are all zero, otherwise an
    ///   [`Inexact`](AmountErrorKind::Inexact) is returned.
    ///
    /// This is the inverse of [`to_decimal_parts`](Self::to_decimal_parts) and
    /// the single place where the backing-int range check lives, so widening the
    /// backing only relaxes the check here and leaves callers untouched.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::{Amount64, AmountErrorKind};
    /// // 1.23 expressed as 123 * 10^-2, retargeted to SCALE = 4.
    /// assert_eq!(Amount64::from_decimal_parts(123, -2), Ok(Amount64::from(123) / Amount64::from(100)));
    /// // Round-trip of an existing value.
    /// let a = Amount64::from(7);
    /// let (m, e) = a.to_decimal_parts();
    /// assert_eq!(Amount64::from_decimal_parts(m, e), Ok(a));
    /// // More fractional digits than a 4-digit type can hold: rejected.
    /// assert_eq!(Amount64::from_decimal_parts(1, -5), Err(AmountErrorKind::Inexact));
    /// ```
    pub const fn from_decimal_parts(
        mantissa: i128,
        exponent: i32,
    ) -> Result<Self, AmountErrorKind> {
        // Zero is exactly representable at any exponent; short-circuit before
        // computing powers of ten that may overflow for extreme exponents.
        if mantissa == 0 {
            return Ok(Decimal::<DIGITS>(0));
        }
        // Decimal places to shift the mantissa by to reach this type's scale.
        // Widen to i64 so the addition cannot overflow regardless of `exponent`.
        let shift = exponent as i64 + Self::SCALE as i64;
        let scaled = if shift >= 0 {
            // Scale up: mantissa * 10^shift.
            let factor = match ipow10_i128(shift) {
                Some(f) => f,
                None => return Err(AmountErrorKind::Overflow),
            };
            match mantissa.checked_mul(factor) {
                Some(v) => v,
                None => return Err(AmountErrorKind::Overflow),
            }
        } else {
            // Scale down: mantissa / 10^(-shift), but only if exact.
            let divisor = match ipow10_i128(-shift) {
                Some(d) => d,
                // 10^(-shift) exceeds i128, yet the mantissa is non-zero here:
                // the value carries far more precision than this type can hold.
                None => return Err(AmountErrorKind::Inexact),
            };
            if mantissa % divisor != 0 {
                return Err(AmountErrorKind::Inexact);
            }
            mantissa / divisor
        };
        // Fit into the backing integer.
        if scaled < i64::MIN as i128 || scaled > i64::MAX as i128 {
            return Err(AmountErrorKind::Overflow);
        }
        Ok(Decimal::<DIGITS>(scaled as i64))
    }

    /// Builds a value from `(mantissa, exponent)`, rounding to this type's scale
    /// with the given [`Rounding`] mode when the input carries more fractional
    /// digits than can be held exactly.
    ///
    /// This is the deliberately-inexact counterpart of
    /// [`from_decimal_parts`](Self::from_decimal_parts): it never returns
    /// [`Inexact`](AmountErrorKind::Inexact). The only failure mode is
    /// [`Overflow`](AmountErrorKind::Overflow), when the value does not fit the
    /// backing integer. Scaling *up* is always exact, so the rounding mode only
    /// matters when digits are dropped.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::{Amount64, Rounding};
    /// // 1.23456 has more than 4 fractional digits; round half-up to 1.2346.
    /// assert_eq!(
    ///     Amount64::from_decimal_parts_rounded(123456, -5, Rounding::HalfUp),
    ///     Ok(Amount64::from(12346) / Amount64::from(10000)),
    /// );
    /// // Trailing zeros are dropped exactly regardless of mode.
    /// assert_eq!(
    ///     Amount64::from_decimal_parts_rounded(1_230_000, -6, Rounding::Down),
    ///     Amount64::from_decimal_parts(1_230_000, -6),
    /// );
    /// ```
    pub const fn from_decimal_parts_rounded(
        mantissa: i128,
        exponent: i32,
        mode: Rounding,
    ) -> Result<Self, AmountErrorKind> {
        if mantissa == 0 {
            return Ok(Decimal::<DIGITS>(0));
        }
        let shift = exponent as i64 + Self::SCALE as i64;
        let scaled = if shift >= 0 {
            // Scale up: always exact.
            let factor = match ipow10_i128(shift) {
                Some(f) => f,
                None => return Err(AmountErrorKind::Overflow),
            };
            match mantissa.checked_mul(factor) {
                Some(v) => v,
                None => return Err(AmountErrorKind::Overflow),
            }
        } else {
            let is_neg = mantissa < 0;
            // `unsigned_abs` avoids the `i128::MIN` overflow that `abs` would hit.
            let mag = mantissa.unsigned_abs();
            let divisor = match ipow10_i128(-shift) {
                Some(d) => d as u128,
                // 10^(-shift) > i128::MAX >= mag, so |value| < 0.5 ULP: rounds to
                // 0, except `Up` rounds away from zero to one ULP.
                None => {
                    let one = match mode {
                        Rounding::Up => {
                            if is_neg {
                                -1
                            } else {
                                1
                            }
                        }
                        _ => 0,
                    };
                    return Ok(Decimal::<DIGITS>(one));
                }
            };
            let quo = mag / divisor;
            let rem = mag % divisor;
            // The divisor is a power of ten >= 10, hence always even: `half` is an
            // exact tie threshold.
            let half = divisor / 2;
            let round_up = match mode {
                Rounding::HalfEven => rem > half || (rem == half && !quo.is_multiple_of(2)),
                Rounding::HalfUp => rem >= half,
                Rounding::HalfDown => rem > half,
                Rounding::Down => false,
                Rounding::Up => rem != 0,
            };
            let q = if round_up { quo + 1 } else { quo } as i128;
            if is_neg { -q } else { q }
        };
        if scaled < i64::MIN as i128 || scaled > i64::MAX as i128 {
            return Err(AmountErrorKind::Overflow);
        }
        Ok(Decimal::<DIGITS>(scaled as i64))
    }

    /// Parses a decimal string, rounding any fractional digits beyond this
    /// type's scale with the given [`Rounding`] mode.
    ///
    /// Like [`FromStr`], but with explicit control over how excess precision is
    /// rounded. [`FromStr`]/[`From<&str>`](From) use [`Rounding::HalfUp`].
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::{Amount64, Rounding};
    /// // Five fractional digits into a 4-digit type, rounded to even.
    /// assert_eq!(
    ///     Amount64::from_str_rounded("1.23455", Rounding::HalfEven),
    ///     Ok(Amount64::from(12346) / Amount64::from(10000)),
    /// );
    /// assert_eq!(
    ///     Amount64::from_str_rounded("1.23465", Rounding::HalfEven),
    ///     Ok(Amount64::from(12346) / Amount64::from(10000)),
    /// );
    /// ```
    pub const fn from_str_rounded(src: &str, mode: Rounding) -> Result<Self, AmountErrorKind> {
        match parse_decimal_i64_rounded(src, DIGITS, mode) {
            Ok(v) => Ok(Decimal::<DIGITS>(v)),
            Err(e) => Err(e),
        }
    }

    /// Parses a decimal string with [`Rounding::HalfUp`], panicking on invalid
    /// input — intended for compile-time constants, where the panic becomes a
    /// compile error.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::Amount64;
    /// use core::str::FromStr;
    /// const PRICE: Amount64 = Amount64::from_str_const("19.99");
    /// assert_eq!(Ok(PRICE), Amount64::from_str("19.99"));
    /// ```
    pub const fn from_str_const(src: &str) -> Self {
        match Self::from_str_rounded(src, Rounding::HalfUp) {
            Ok(v) => v,
            Err(_) => panic!("invalid decimal literal"),
        }
    }

    /// Computes the absolute value of self.
    /// # Examples
    ///
    /// ```
    /// use fin_decimal::Amount64;
    /// let f = Amount64::from(3);
    /// let g = Amount64::from(-4);
    ///
    /// assert_eq!(f.abs(), 3);
    /// assert_eq!(g.abs(), 4);
    /// ```
    #[inline]
    pub const fn abs(self) -> Self {
        Decimal::<DIGITS>(self.0.abs())
    }

    /// Checked integer addition. Computes `self + rhs`, returning `None` if overflow occurred.
    #[inline]
    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
        match self.0.checked_add(rhs.0) {
            Some(v) => Some(Decimal::<DIGITS>(v)),
            None => None,
        }
    }

    /// Checked integer subtraction. Computes `self - rhs`, returning `None` if overflow occurred.
    #[inline]
    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
        match self.0.checked_sub(rhs.0) {
            Some(v) => Some(Decimal::<DIGITS>(v)),
            None => None,
        }
    }

    /// Sign and 4-limb magnitude (zero-extended), for the shared
    /// formatting code in [`common`](crate::common).
    #[inline]
    pub(crate) const fn sign_mag4(self) -> (bool, [u64; 4]) {
        (self.0 < 0, [self.0.unsigned_abs(), 0, 0, 0])
    }

    /// Checked integer multiplication. Computes `self * rhs`, returning `None` if overflow occurred.
    #[inline]
    pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
        let (an, am) = i64_sign_mag(self.0);
        let (bn, bm) = i64_sign_mag(rhs.0);
        match limbs::dec_mul::<DIGITS, 1, 2>(an, &am, bn, &bm, Rounding::HalfUp) {
            Some((neg, mag)) => Some(Decimal::<DIGITS>(i64_from_sign_mag(neg, mag))),
            None => None,
        }
    }

    /// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0` or the division results in overflow.
    #[inline]
    pub fn checked_div(self, rhs: Self) -> Option<Self> {
        let (an, am) = i64_sign_mag(self.0);
        let (bn, bm) = i64_sign_mag(rhs.0);
        limbs::dec_div::<DIGITS, 1, 2>(an, &am, bn, &bm, Rounding::HalfUp)
            .map(|(neg, mag)| Decimal::<DIGITS>(i64_from_sign_mag(neg, mag)))
    }

    /// Checked remainder. Computes `self % rhs`, returning `None` if
    /// `rhs == 0`. (The remainder itself cannot overflow: its magnitude
    /// never exceeds the divisor's.)
    #[inline]
    pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
        if rhs.0 == 0 {
            None
        } else {
            Some(Decimal::<DIGITS>(self.0 % rhs.0))
        }
    }

    /// Takes the reciprocal (inverse) of a number, 1/x.
    ///
    /// # Panics
    /// Panics if `self` is zero (like core's `/`) or the result overflows;
    /// [`checked_recip`](Self::checked_recip) is the non-panicking form.
    #[inline]
    pub fn recip(self) -> Self {
        if self.0 == 0 {
            panic!("attempt to divide by zero");
        }
        match self.checked_recip() {
            Some(v) => v,
            None => panic!("attempt to divide with overflow"),
        }
    }

    /// Checked reciprocal: `None` if `self` is zero or `1 / self` overflows
    /// (on this backing the reciprocal's mantissa can reach
    /// `10^(2 * DIGITS)`, which exceeds the range for `DIGITS >= 10`).
    #[inline]
    pub fn checked_recip(self) -> Option<Self> {
        Self::ONE.checked_div_rounded(self, Rounding::HalfUp)
    }

    /// Returns the integer part of a number.
    ///
    /// # Examples
    ///
    /// ```
    /// use fin_decimal::Amount64;
    /// let f = Amount64::from_f64(3.7_f64).unwrap();
    /// let g = Amount64::from_f64(3.0_f64).unwrap();
    /// let h = Amount64::from_f64(-3.7_f64).unwrap();
    ///
    /// assert_eq!(f.trunc(), 3.0);
    /// assert_eq!(g.trunc(), 3.0);
    /// assert_eq!(h.trunc(), -3.0);
    /// ```
    #[inline]
    pub fn trunc(self) -> Self {
        Decimal::<DIGITS>(self.0 - self.0 % Self::SCALE_INT)
    }

    /// Returns the largest integer less than or equal to a number.
    ///
    /// # Examples
    ///
    /// ```
    /// use fin_decimal::Amount64;
    /// let f = Amount64::from_f64(3.7_f64).unwrap();
    /// let g = Amount64::from_f64(3.0_f64).unwrap();
    /// let h = Amount64::from_f64(-3.7_f64).unwrap();
    ///
    /// assert_eq!(f.floor(), 3);
    /// assert_eq!(g.floor(), 3);
    /// assert_eq!(h.floor(), -4);
    /// ```
    ///
    /// # Panics
    /// Panics if rounding at the very edge of the range overflows (see
    /// [`round_to`](Self::round_to)).
    #[inline]
    pub const fn floor(self) -> Self {
        self.round_to(Rounding::Down)
    }

    /// Returns the smallest integer greater than or equal to a number.
    ///
    /// # Examples
    ///
    /// ```
    /// use fin_decimal::Amount64;
    /// let f = Amount64::from_f64(3.01_f64).unwrap();
    /// let g = Amount64::from_f64(4.0_f64).unwrap();
    /// let h = Amount64::from_f64(-3.7_f64).unwrap();
    ///
    /// assert_eq!(f.ceil(), 4);
    /// assert_eq!(g.ceil(), 4);
    /// assert_eq!(h.ceil(), -3);
    /// ```
    ///
    /// # Panics
    /// Panics if rounding at the very edge of the range overflows (see
    /// [`round_to`](Self::round_to)).
    #[inline]
    pub const fn ceil(self) -> Self {
        self.round_to(Rounding::Up)
    }

    /// Returns the nearest integer to a number. Round half-way cases away from
    /// `0.0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fin_decimal::Amount64;
    /// let f = Amount64::from(3.3_f64);
    /// let g = Amount64::from(-3.3_f64);
    ///
    /// assert_eq!(f.round(), 3);
    /// assert_eq!(g.round(), -3);
    /// ```
    ///
    /// # Panics
    /// Panics if rounding at the very edge of the range overflows (see
    /// [`round_to`](Self::round_to)).
    #[inline]
    pub const fn round(self) -> Self {
        self.round_to(Rounding::HalfUp)
    }

    /// Rounding to 1/100th (0.01) half-way cases away from `0.0`:
    /// equivalent to [`round_dp`](Self::round_dp)`(2, Rounding::HalfUp)`.
    ///
    /// For `DIGITS <= 2` this is the identity (there is nothing beyond two
    /// fractional digits to round). Note this is a behavior change in
    /// 0.3.3: earlier versions incorrectly bumped every `Decimal<2>` value
    /// by one ulp and panicked with a division by zero on `Decimal<0>` and
    /// `Decimal<1>`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fin_decimal::Amount64;
    /// assert_eq!(Amount64::from(3.356_f64).round100(), Amount64::from(3.36_f64));
    /// assert_eq!(Amount64::from(3.354_f64).round100(), Amount64::from(3.35_f64));
    /// ```
    ///
    /// # Panics
    /// Panics if rounding away from zero at the very edge of the range
    /// overflows.
    #[inline]
    pub const fn round100(self) -> Self {
        self.round_dp(2, Rounding::HalfUp)
    }

    /// Rounds to `dp` fractional digits with the given mode, keeping the
    /// type and scale: digits beyond `dp` become zero. `dp >= DIGITS` is
    /// the identity; `dp == 0` matches [`round_to`](Self::round_to).
    ///
    /// The typical use is carrying full precision internally while rounding
    /// at a regulated boundary (e.g. tax at 2 decimal places on an
    /// 8-digit-rate computation). Usable in const contexts.
    ///
    /// # Panics
    /// Panics if rounding away from zero at the very edge of the range
    /// overflows; [`checked_round_dp`](Self::checked_round_dp) is the
    /// non-panicking form.
    pub const fn round_dp(self, dp: u8, mode: Rounding) -> Self {
        match self.checked_round_dp(dp, mode) {
            Some(v) => v,
            None => panic!("attempt to round with overflow"),
        }
    }

    /// Checked form of [`round_dp`](Self::round_dp): `None` if rounding
    /// away from zero at the very edge of the range overflows.
    pub const fn checked_round_dp(self, dp: u8, mode: Rounding) -> Option<Self> {
        if dp >= DIGITS {
            return Some(self);
        }
        // `step` is a runtime divisor here (dp is a runtime parameter), so
        // native word division is the right tool.
        let step = limbs::upow10((DIGITS - dp) as u32);
        let neg = self.0 < 0;
        let mag = self.0.unsigned_abs();
        let q = mag / step;
        let r = mag % step;
        let up = limbs::round_up_by_cmp(
            limbs::cmp_twice_rem_u64(r, step),
            r == 0,
            q & 1 != 0,
            neg,
            mode,
        );
        // (q + up) * step cannot wrap u64: for DIGITS <= 18 it is at most
        // mag - r + step < 2^63 + 10^18; at DIGITS = 19 (supported here,
        // step = 10^19 > mag) the division gives q = 0 and the product is
        // at most step itself. Either way it may still exceed the i64
        // range, which the check below catches.
        let scaled = (q + up as u64) * step;
        if scaled > i64::MAX as u64 {
            return None;
        }
        Some(Decimal::<DIGITS>(i64_from_sign_mag(neg, [scaled])))
    }

    /// Splits `self` into `n` parts that sum back to `self` **exactly**:
    /// `high_count` parts one unit in the last place larger than the
    /// remaining `low_count` parts (largest-remainder allocation). `None`
    /// if `n` is zero. Usable in const contexts.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::Amount64;
    /// let split = Amount64::from_str_const("100.00").checked_split_evenly(3).unwrap();
    /// // 1 part of 33.3334 + 2 parts of 33.3333 == 100.0000 exactly.
    /// assert_eq!(split.high, Amount64::from_str_const("33.3334"));
    /// assert_eq!(split.high_count, 1);
    /// assert_eq!(split.low, Amount64::from_str_const("33.3333"));
    /// assert_eq!(split.low_count, 2);
    /// ```
    pub const fn checked_split_evenly(self, n: u32) -> Option<EvenSplit<Self>> {
        if n == 0 {
            return None;
        }
        let neg = self.0 < 0;
        let mag = self.0.unsigned_abs();
        let q = mag / n as u64;
        let r = (mag % n as u64) as u32;
        let low = Decimal::<DIGITS>(i64_from_sign_mag(neg, [q]));
        // For n == 1 the split is exact (r == 0), so q + 1 below never
        // overflows: an inexact split implies n >= 2, hence q <= MAX / 2.
        let (high, high_count) = if r == 0 {
            (low, 0)
        } else {
            (Decimal::<DIGITS>(i64_from_sign_mag(neg, [q + 1])), r)
        };
        Some(EvenSplit {
            high,
            high_count,
            low,
            low_count: n - high_count,
        })
    }

    /// Panicking form of
    /// [`checked_split_evenly`](Self::checked_split_evenly).
    ///
    /// # Panics
    /// Panics if `n` is zero (like core's `/`).
    pub const fn split_evenly(self, n: u32) -> EvenSplit<Self> {
        match self.checked_split_evenly(n) {
            Some(v) => v,
            None => panic!("attempt to divide by zero"),
        }
    }

    /// Explicitly rounds the value using the specified rounding mode.
    ///
    /// # Panics
    /// Panics if rounding away from zero at the very edge of the range
    /// overflows.
    pub const fn round_to(self, mode: Rounding) -> Self {
        match self.checked_round_to(mode) {
            Some(v) => v,
            None => panic!("attempt to round with overflow"),
        }
    }

    /// Checked form of [`round_to`](Self::round_to): `None` if rounding away
    /// from zero at the very edge of the range overflows.
    pub const fn checked_round_to(self, mode: Rounding) -> Option<Self> {
        let frac = self.0 % Decimal::<DIGITS>::SCALE_INT;
        if frac == 0 {
            return Some(self);
        }

        let int_part = self.0 - frac;

        let mut add_one = false;
        let mut sub_one = false;

        match mode {
            Rounding::HalfEven => {
                let half = Decimal::<DIGITS>::SCALE_INT_HALF;
                let is_even = (int_part / Decimal::<DIGITS>::SCALE_INT) % 2 == 0;

                if frac > half {
                    add_one = true;
                } else if frac < -half {
                    sub_one = true;
                } else if frac == half {
                    if !is_even {
                        add_one = true;
                    }
                } else if frac == -half && !is_even {
                    sub_one = true;
                }
            }
            Rounding::HalfUp => {
                let half = Decimal::<DIGITS>::SCALE_INT_HALF;
                if frac >= half {
                    add_one = true;
                } else if frac <= -half {
                    sub_one = true;
                }
            }
            Rounding::HalfDown => {
                let half = Decimal::<DIGITS>::SCALE_INT_HALF;
                if frac > half {
                    add_one = true;
                } else if frac < -half {
                    sub_one = true;
                }
            }
            Rounding::Down => {
                if frac < 0 {
                    sub_one = true;
                }
            }
            Rounding::Up => {
                if frac > 0 {
                    add_one = true;
                }
            }
        }

        // Checked: rounding away from zero at the very edge of the range
        // must be caught in every build profile, never wrap in release
        // builds of consumer crates (this generic body is monomorphized
        // under the consumer's overflow-checks setting).
        let step = if add_one {
            Decimal::<DIGITS>::SCALE_INT
        } else if sub_one {
            -Decimal::<DIGITS>::SCALE_INT
        } else {
            0
        };
        match int_part.checked_add(step) {
            Some(res) => Some(Decimal::<DIGITS>(res)),
            None => None,
        }
    }

    /// Multiply by another decimal, explicitly applying the given rounding mode.
    ///
    /// The right-hand side may have a different scale: the exact product is
    /// rounded once to `self`'s scale, so an amount times a high-precision
    /// rate needs no intermediate conversion.
    ///
    /// Usable in const contexts, so multiplication chains can be evaluated at
    /// compile time.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::{Amount64, Rate64, Rounding};
    /// let amount = Amount64::from_str_const("125.00");
    /// let rate = Rate64::from_str_const("0.0725"); // 7.25%, 8-digit scale
    /// assert_eq!(
    ///     amount.mul_rounded(rate, Rounding::HalfUp),
    ///     Amount64::from_str_const("9.0625")
    /// );
    /// ```
    ///
    /// # Panics
    /// Panics if the result overflows (like core integer arithmetic in debug
    /// builds); [`checked_mul_rounded`](Self::checked_mul_rounded) is the
    /// non-panicking form.
    pub const fn mul_rounded<const RHS_DIGITS: u8>(
        self,
        rhs: Decimal<RHS_DIGITS>,
        mode: Rounding,
    ) -> Self {
        match self.checked_mul_rounded(rhs, mode) {
            Some(v) => v,
            None => panic!("attempt to multiply with overflow"),
        }
    }

    /// Checked form of [`mul_rounded`](Self::mul_rounded): `None` if the
    /// result overflows.
    #[inline]
    pub const fn checked_mul_rounded<const RHS_DIGITS: u8>(
        self,
        rhs: Decimal<RHS_DIGITS>,
        mode: Rounding,
    ) -> Option<Self> {
        let (an, am) = i64_sign_mag(self.0);
        let (bn, bm) = i64_sign_mag(rhs.0);
        match limbs::dec_mul::<RHS_DIGITS, 1, 2>(an, &am, bn, &bm, mode) {
            Some((neg, mag)) => Some(Decimal::<DIGITS>(i64_from_sign_mag(neg, mag))),
            None => None,
        }
    }

    /// Divide by another decimal, explicitly applying the given rounding mode.
    ///
    /// # Panics
    /// Panics if `rhs` is zero (like core's `/`) or the result overflows;
    /// [`checked_div_rounded`](Self::checked_div_rounded) is the
    /// non-panicking form.
    pub fn div_rounded(self, rhs: Self, mode: Rounding) -> Self {
        self.div_rounded_to::<DIGITS>(rhs, mode)
    }

    /// Checked form of [`div_rounded`](Self::div_rounded): `None` if `rhs`
    /// is zero or the result overflows.
    #[inline]
    pub fn checked_div_rounded(self, rhs: Self, mode: Rounding) -> Option<Self> {
        self.checked_div_rounded_to::<DIGITS>(rhs, mode)
    }

    /// Divide by another decimal of the same scale, producing the quotient at
    /// an explicitly chosen scale with the given rounding mode. The exact
    /// quotient is rounded once at `TO_DIGITS` digits, so a proportion of two
    /// amounts can be taken directly as a higher-precision rate.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::{Amount64, Rate64, Rounding};
    /// let part = Amount64::from(2);
    /// let whole = Amount64::from(3);
    /// assert_eq!(
    ///     part.div_rounded_to::<8>(whole, Rounding::HalfUp),
    ///     Rate64::from_str_const("0.66666667")
    /// );
    /// ```
    ///
    /// # Panics
    /// Panics if `rhs` is zero (like core's `/`) or the result overflows;
    /// [`checked_div_rounded_to`](Self::checked_div_rounded_to) is the
    /// non-panicking form.
    pub fn div_rounded_to<const TO_DIGITS: u8>(
        self,
        rhs: Self,
        mode: Rounding,
    ) -> Decimal<TO_DIGITS> {
        if rhs.0 == 0 {
            panic!("attempt to divide by zero");
        }
        match self.checked_div_rounded_to::<TO_DIGITS>(rhs, mode) {
            Some(v) => v,
            None => panic!("attempt to divide with overflow"),
        }
    }

    /// Checked form of [`div_rounded_to`](Self::div_rounded_to): `None` if
    /// `rhs` is zero or the result overflows.
    #[inline]
    pub fn checked_div_rounded_to<const TO_DIGITS: u8>(
        self,
        rhs: Self,
        mode: Rounding,
    ) -> Option<Decimal<TO_DIGITS>> {
        let (an, am) = i64_sign_mag(self.0);
        let (bn, bm) = i64_sign_mag(rhs.0);
        limbs::dec_div::<TO_DIGITS, 1, 2>(an, &am, bn, &bm, mode)
            .map(|(neg, mag)| Decimal::<TO_DIGITS>(i64_from_sign_mag(neg, mag)))
    }

    /// Divide by an integer, explicitly applying the given rounding mode: the
    /// exact quotient is rounded once at the type's own scale. Equivalent to
    /// `div_rounded` by `Decimal::from(n)` but skips re-scaling the dividend,
    /// staying a single native word division, and accepts any `i64` divisor
    /// (converting a huge `n` could itself overflow).
    ///
    /// Usable in const contexts, so fixed splits can be evaluated at compile
    /// time.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::{Amount64, Rounding};
    /// let total = Amount64::from_str_const("100.0001");
    /// assert_eq!(
    ///     total.div_int_rounded(3, Rounding::HalfUp),
    ///     Amount64::from_str_const("33.3334")
    /// );
    /// ```
    ///
    /// # Panics
    /// Panics if `n` is zero (like core's `/`);
    /// [`checked_div_int_rounded`](Self::checked_div_int_rounded) is the
    /// non-panicking form. The result itself cannot overflow: its magnitude
    /// never exceeds `self`'s (rounding up only happens for `|n| >= 2`).
    pub const fn div_int_rounded(self, n: i64, mode: Rounding) -> Self {
        match self.checked_div_int_rounded(n, mode) {
            Some(v) => v,
            None => panic!("attempt to divide by zero"),
        }
    }

    /// Checked form of [`div_int_rounded`](Self::div_int_rounded): `None`
    /// only if `n` is zero (the result cannot overflow).
    #[inline]
    pub const fn checked_div_int_rounded(self, n: i64, mode: Rounding) -> Option<Self> {
        if n == 0 {
            return None;
        }
        let neg = (self.0 < 0) != (n < 0);
        let a = self.0.unsigned_abs();
        let d = n.unsigned_abs();
        let q = a / d;
        let r = a % d;
        let up = limbs::round_up_by_cmp(
            limbs::cmp_twice_rem_u64(r, d),
            r == 0,
            q & 1 != 0,
            neg,
            mode,
        );
        Some(Decimal::<DIGITS>(i64_from_sign_mag(neg, [q + up as u64])))
    }

    /// Square root with the given rounding mode, or `None` for a negative
    /// value or (only possible at `DIGITS = 19`, where every value is below
    /// one and a square root therefore *grows*) result overflow.
    ///
    /// The exact root of `self` is rounded once at the type's own scale:
    /// the result is the correctly rounded decimal square root, computed as
    /// the integer square root of `mantissa * 10^DIGITS`. For the half
    /// modes a tie cannot occur (`(s + 1/2)^2` is never an integer), so
    /// `HalfUp`, `HalfDown` and `HalfEven` always agree here.
    ///
    /// Usable in const contexts.
    pub const fn checked_sqrt_rounded(self, mode: Rounding) -> Option<Self> {
        if self.0 < 0 {
            return None;
        }
        let n = self.0 as u128 * const { limbs::upow10(DIGITS as u32) } as u128;
        // The shared u128 core: core's `u64::isqrt` for single-limb inputs
        // (native word divisions only), the division-free f64-seeded Newton
        // for wider ones. (`u128::isqrt` benches fastest on x86 but its
        // codegen contains a `__udivti3` libcall, which the crate bans; the
        // asm probes hold this path to no-128-bit-builtins.)
        let (s, rem_zero, rem_gt_root) = limbs::isqrt_u128_with_rem(n);
        let up = limbs::sqrt_round_up(mode, rem_zero, rem_gt_root);
        let mag = s + up as u64;
        if mag >> 63 != 0 {
            return None;
        }
        Some(Decimal::<DIGITS>(mag as i64))
    }

    /// Square root, explicitly applying the given rounding mode. See
    /// [`checked_sqrt_rounded`](Self::checked_sqrt_rounded).
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::{Amount64, Rounding};
    /// let two = Amount64::from(2);
    /// assert_eq!(two.sqrt_rounded(Rounding::HalfUp), Amount64::from_str_const("1.4142"));
    /// assert_eq!(two.sqrt_rounded(Rounding::Up), Amount64::from_str_const("1.4143"));
    /// ```
    ///
    /// # Panics
    /// Panics if `self` is negative (with core's `isqrt` message) or the
    /// result overflows;
    /// [`checked_sqrt_rounded`](Self::checked_sqrt_rounded) is the
    /// non-panicking form.
    pub const fn sqrt_rounded(self, mode: Rounding) -> Self {
        if self.0 < 0 {
            panic!("argument of integer square root cannot be negative");
        }
        match self.checked_sqrt_rounded(mode) {
            Some(v) => v,
            None => panic!("attempt to compute square root with overflow"),
        }
    }

    /// Square root, rounded half-up at the type's own scale (the operators'
    /// default rounding). See
    /// [`checked_sqrt_rounded`](Self::checked_sqrt_rounded).
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::Amount64;
    /// assert_eq!(Amount64::from_str_const("2.25").sqrt(), Amount64::from_str_const("1.5"));
    /// ```
    ///
    /// # Panics
    /// Panics if `self` is negative or the result overflows;
    /// [`checked_sqrt`](Self::checked_sqrt) is the non-panicking form.
    pub const fn sqrt(self) -> Self {
        self.sqrt_rounded(Rounding::HalfUp)
    }

    /// Checked form of [`sqrt`](Self::sqrt) (half-up rounding), mirroring
    /// core's `checked_isqrt` on signed integers: `None` for a negative
    /// value (or overflow, see
    /// [`checked_sqrt_rounded`](Self::checked_sqrt_rounded)).
    #[inline]
    pub const fn checked_sqrt(self) -> Option<Self> {
        self.checked_sqrt_rounded(Rounding::HalfUp)
    }

    /// `self * b / c` on the exact 128-bit product with a single rounding at
    /// the end, or `None` if `c` is zero or the result overflows.
    ///
    /// The muldiv/pro-rata primitive: allocating an amount by the proportion
    /// `b / c` this way avoids the double rounding of first taking the ratio
    /// and then multiplying by it. `b` and `c` share a scale — any scale,
    /// since it cancels in `b / c` — and the result keeps `self`'s scale.
    pub fn checked_mul_div_rounded<const S: u8>(
        self,
        b: Decimal<S>,
        c: Decimal<S>,
        mode: Rounding,
    ) -> Option<Self> {
        let (an, am) = i64_sign_mag(self.0);
        let (bn, bm) = i64_sign_mag(b.0);
        let (cn, cm) = i64_sign_mag(c.0);
        limbs::dec_mul_div::<1, 2>(an, &am, bn, &bm, cn, &cm, mode)
            .map(|(neg, mag)| Decimal::<DIGITS>(i64_from_sign_mag(neg, mag)))
    }

    /// `self * b / c` on the exact 128-bit product with a single rounding at
    /// the end. See
    /// [`checked_mul_div_rounded`](Self::checked_mul_div_rounded).
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::{Amount64, Rounding};
    /// // Allocate a total pro rata by 1/3 without an intermediate rate.
    /// let total = Amount64::from_str_const("100.00");
    /// let share = total.mul_div_rounded(Amount64::from(1), Amount64::from(3), Rounding::HalfUp);
    /// assert_eq!(share, Amount64::from_str_const("33.3333"));
    /// ```
    ///
    /// # Panics
    /// Panics if `c` is zero (like core's `/`) or the result overflows;
    /// [`checked_mul_div_rounded`](Self::checked_mul_div_rounded) is the
    /// non-panicking form.
    pub fn mul_div_rounded<const S: u8>(
        self,
        b: Decimal<S>,
        c: Decimal<S>,
        mode: Rounding,
    ) -> Self {
        if c.0 == 0 {
            panic!("attempt to divide by zero");
        }
        // The 2W-limb product is exact, so overflow is always quotient-driven.
        match self.checked_mul_div_rounded(b, c, mode) {
            Some(v) => v,
            None => panic!("attempt to divide with overflow"),
        }
    }

    #[inline]
    /// Returns the fractional part of a number.
    ///
    /// # Examples
    ///
    /// ```
    /// use fin_decimal::Amount64;
    /// let x = Amount64::from(3.6_f64);
    /// let y = Amount64::from(-3.6_f64);
    /// let abs_difference_x = (x.fract() - 0.6).abs();
    /// let abs_difference_y = (y.fract() - (-0.6)).abs();
    ///
    /// assert!(abs_difference_x < 1e-10);
    /// assert!(abs_difference_y < 1e-10);
    /// ```
    pub const fn fract(self) -> Self {
        // fractional part would be a reminder of division by the scaler
        Decimal::<DIGITS>(self.0 % Self::SCALE_INT)
    }

    /// Returns `true` if `self` is positive and `false` if the number is zero or negative.
    /// # Examples
    /// Basic usage:
    /// ```
    /// use fin_decimal::Amount64;
    /// assert_eq!(Amount64::from(10).is_positive(), true);
    /// assert_eq!(Amount64::from(-10).is_positive(), false);
    /// ```
    #[inline]
    pub const fn is_positive(self) -> bool {
        self.0 > 0
    }

    /// Returns `true` if `self` is negative and `false` if the number is zero or positive.
    /// # Examples
    /// Basic usage:
    /// ```
    /// use fin_decimal::Amount64;
    /// assert_eq!(Amount64::from(10).is_negative(), false);
    /// assert_eq!(Amount64::from(-10).is_negative(), true);
    /// ```
    #[inline]
    pub const fn is_negative(self) -> bool {
        self.0 < 0
    }

    /// Returns a number that represents the sign of `self`.
    ///
    /// - `1.0` if the number is positive
    /// - `-1.0` if the number is negative
    /// - `0` if the number is `0`
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::Amount64;
    /// assert_eq!(Amount64::from(10).signum(), Amount64::ONE);
    /// assert_eq!(Amount64::from(-10).signum(), Amount64::MINUS_ONE);
    /// assert_eq!(Amount64::from(0).signum(), Amount64::ZERO);
    /// ```
    pub fn signum(self) -> Self {
        match (self.0 < 0, self.0 > 0) {
            (true, _) => Self::MINUS_ONE,
            (false, false) => Self::ZERO,
            (_, _) => Self::ONE,
        }
    }

    /// Raw transmutation to u64.
    /// This is currently identical to transmute::<f64, u64>(self) on all platforms.
    /// See from_bits for some discussion of the portability of this operation
    /// (there are almost no issues).  Note that this function is distinct from as casting,
    /// which attempts to preserve the numeric value, and not the bitwise value.
    /// # Examples
    /// ```
    /// use fin_decimal::Amount64;
    /// assert!(Amount64::from(1.0).to_bits() != 1.0 as u64); // to_bits() is not casting!
    /// assert_eq!(Amount64::from(2.5).to_bits(), (Amount64::SCALE_INT*2 + Amount64::SCALE_INT_HALF) as u64);
    /// ```
    #[inline]
    pub const fn to_bits(self) -> u64 {
        self.0 as u64
    }

    /// Raw transmutation from u64.
    /// This is currently identical to transmute::<u64, f64>(v) on all platforms.
    /// # Examples
    /// ```
    /// use fin_decimal::Amount64;
    /// assert_eq!(Amount64::from_bits((Amount64::SCALE_INT*2 + Amount64::SCALE_INT_HALF) as u64), Amount64::from(2.5));
    /// ```
    #[inline]
    pub const fn from_bits(v: u64) -> Self {
        // SAFETY: `u64` is a plain old datatype so we can always transmute from it
        // It turns out the safety issues with sNaN were overblown! Hooray!
        Decimal::<DIGITS>(v as i64)
    }

    /// Reverses the byte order of the Amount64. Primary use case - serialization.
    /// ```
    /// use fin_decimal::Amount64;
    /// let n = Amount64::from_bits(0x1234567890123456u64);
    /// let m = n.swap_bytes();
    /// assert_eq!(m.to_bits(), 0x5634129078563412);
    /// ```
    #[inline]
    pub const fn swap_bytes(self) -> Self {
        Decimal::<DIGITS>(self.0.swap_bytes())
    }

    /// Return the memory representation of this integer as a byte array in big-endian (network) byte order.
    /// # Examples
    /// Basic usage:
    /// ```
    /// use fin_decimal::Amount64;
    /// let bytes = Amount64::from_bits(0x1234567890123456u64).to_be_bytes();
    /// assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);
    /// ```
    #[inline]
    pub const fn to_be_bytes(self) -> [u8; mem::size_of::<i64>()] {
        self.0.to_be().to_ne_bytes()
    }

    /// Return the memory representation of this integer as a byte array in little-endian byte order.
    /// # Examples
    /// Basic usage:
    /// ```
    /// use fin_decimal::Amount64;
    /// let bytes = Amount64::from_bits(0x1234567890123456u64).to_le_bytes();
    /// assert_eq!(bytes, [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);
    /// ```
    #[inline]
    pub const fn to_le_bytes(self) -> [u8; mem::size_of::<i64>()] {
        self.0.to_le().to_ne_bytes()
    }

    /// Return the memory representation of this integer as a byte array in native byte order.
    /// As the target platform's native endianness is used, portable code should use to_be_bytes
    /// or to_le_bytes, as appropriate, instead.
    /// # Examples
    /// Basic usage:
    /// ```
    /// use fin_decimal::Amount64;
    /// let bytes = Amount64::from_bits(0x1234567890123456u64).to_le_bytes();
    /// assert_eq!(bytes,
    /// if cfg!(target_endian = "big") {
    ///        [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]
    ///     } else {
    ///        [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]
    ///     }
    /// );
    /// ```
    #[inline]
    pub fn to_ne_bytes(self) -> [u8; mem::size_of::<i64>()] {
        #[repr(C)]
        union Bytes<const DIGITS: u8> {
            val: core::mem::ManuallyDrop<Decimal<DIGITS>>,
            bytes: [u8; mem::size_of::<i64>()],
        }
        // SAFETY: integers are plain old datatypes so we can always transmute them to
        // arrays of bytes
        unsafe {
            Bytes {
                val: core::mem::ManuallyDrop::new(self),
            }
            .bytes
        }
    }

    /// Create an integer value from its memory representation as a byte array in native endianness.
    /// As the target platform's native endianness is used, portable code likely wants to use from_be_bytes
    /// or from_le_bytes, as appropriate instead.
    ///
    /// # Examples
    /// Basic usage:
    /// ```
    /// use fin_decimal::Amount64;
    /// let value = Amount64::from_ne_bytes(if cfg!(target_endian = "big") {
    ///                 [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]
    ///             } else {
    ///                 [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]
    ///             });
    /// assert_eq!(value,Amount64::from_bits(0x1234567890123456u64));
    /// ```
    #[inline]
    pub fn from_ne_bytes(bytes: [u8; mem::size_of::<i64>()]) -> Self {
        #[repr(C)]
        union Bytes<const DIGITS: u8> {
            val: core::mem::ManuallyDrop<Decimal<DIGITS>>,
            bytes: [u8; mem::size_of::<i64>()],
        }
        // SAFETY: integers are plain old datatypes so we can always transmute to them
        unsafe { core::mem::ManuallyDrop::into_inner(Bytes { bytes }.val) }
    }

    /// Create an integer value from its representation as a byte array in big endian.
    ///
    /// # Examples
    /// Basic usage:
    /// ```
    /// use fin_decimal::Amount64;
    /// let value = Amount64::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);
    /// assert_eq!(value,Amount64::from_bits(0x1234567890123456u64));
    /// ```
    #[inline]
    pub fn from_be_bytes(bytes: [u8; mem::size_of::<i64>()]) -> Self {
        Self::from_bits(u64::from_be_bytes(bytes))
    }

    /// Create an integer value from its representation as a byte array in little endian.
    ///
    /// # Examples
    /// Basic usage:
    /// ```
    /// use fin_decimal::Amount64;
    /// let value = Amount64::from_le_bytes([0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);
    /// assert_eq!(value,Amount64::from_bits(0x1234567890123456u64));
    /// ```
    #[inline]
    pub fn from_le_bytes(bytes: [u8; mem::size_of::<i64>()]) -> Self {
        Self::from_bits(u64::from_le_bytes(bytes))
    }

    /// Raises a number to an integer power.
    ///
    /// # Examples
    ///
    /// ```
    /// use fin_decimal::Amount64;
    /// let x = Amount64::from(2.0_f64);
    /// let abs_difference = (x.powi(2) - (x * x)).abs();
    ///
    /// assert!(abs_difference < 1e-10);
    /// ```
    ///
    /// # Panics
    /// Panics if an intermediate product overflows;
    /// [`checked_powi`](Self::checked_powi) is the non-panicking form.
    #[inline]
    pub const fn powi(self, exp: u32) -> Self {
        match self.checked_powi(exp) {
            Some(v) => v,
            None => panic!("attempt to multiply with overflow"),
        }
    }

    /// Checked form of [`powi`](Self::powi): `None` if an intermediate
    /// product overflows. Each step rounds `HalfUp` at the type's scale,
    /// like `powi`.
    pub const fn checked_powi(self, mut exp: u32) -> Option<Self> {
        let mut base = self;
        let mut acc = Self::ONE;
        while exp > 1 {
            if (exp & 1) == 1 {
                acc = match base.checked_mul_rounded(acc, Rounding::HalfUp) {
                    Some(v) => v,
                    None => return None,
                };
            }
            exp /= 2;
            base = match base.checked_mul_rounded(base, Rounding::HalfUp) {
                Some(v) => v,
                None => return None,
            };
        }
        // The final bit of the exponent is handled separately: squaring the
        // base afterwards is unnecessary and could overflow needlessly.
        if exp == 1 {
            acc = match base.checked_mul_rounded(acc, Rounding::HalfUp) {
                Some(v) => v,
                None => return None,
            };
        }
        Some(acc)
    }

    //pub const fn div_euclid(self, rhs: Self) -> Self {
    //    let q = self / rhs;
    //    if self % rhs < 0 {
    //        return if rhs > 0 { q - 1 } else { q + 1 }
    //    }
    //    q
    //}

    /// Restrict a value to a certain interval.
    /// Returns max if self is greater than max, and min if self is less than min.
    /// Otherwise this returns self.
    /// # Examples
    ///
    /// ```
    /// use fin_decimal::Amount64;
    /// assert_eq!(Amount64::from(2).clamp(Amount64::MINUS_ONE,Amount64::ONE), Amount64::ONE);
    /// assert_eq!(Amount64::from(0).clamp(Amount64::MINUS_ONE,Amount64::ONE), Amount64::ZERO);
    /// ```
    #[inline]
    pub fn clamp(self, min: Self, max: Self) -> Self {
        if self.0 < min.0 {
            Decimal::<DIGITS>(min.0)
        } else if self.0 > max.0 {
            Decimal::<DIGITS>(max.0)
        } else {
            self
        }
    }

    /// Returns the minimum of the two numbers.
    #[inline]
    pub fn min(self, other: Self) -> Self {
        if self <= other { self } else { other }
    }

    /// Returns the maximum of the two numbers.
    #[inline]
    pub fn max(self, other: Self) -> Self {
        if self >= other { self } else { other }
    }
}

impl<const DIGITS: u8> PartialOrd<i64> for Decimal<DIGITS> {
    #[inline]
    fn partial_cmp(&self, other: &i64) -> Option<Ordering> {
        PartialOrd::partial_cmp(&self.0, &(*other * Self::SCALE_INT))
    }
}

impl<const DIGITS: u8> PartialOrd<f64> for Decimal<DIGITS> {
    #[inline]
    fn partial_cmp(&self, other: &f64) -> Option<Ordering> {
        PartialOrd::partial_cmp(&(self.0 as f64), &(*other * Self::SCALE_F64))
    }
}

impl<const DIGITS: u8> PartialOrd<Decimal<DIGITS>> for i64 {
    #[inline]
    fn partial_cmp(&self, other: &Decimal<DIGITS>) -> Option<Ordering> {
        PartialOrd::partial_cmp(&(self * Decimal::<DIGITS>::SCALE_INT), &other.0)
    }
}

impl<const DIGITS: u8> PartialEq<i64> for Decimal<DIGITS> {
    #[inline]
    fn eq(&self, other: &i64) -> bool {
        self.0 == *other * Self::SCALE_INT
    }
}

impl<const DIGITS: u8> PartialEq<f64> for Decimal<DIGITS> {
    #[inline]
    fn eq(&self, other: &f64) -> bool {
        self.0 as f64 == *other * Self::SCALE_F64
    }
}

impl<const DIGITS: u8> PartialEq<Decimal<DIGITS>> for i64 {
    #[inline]
    fn eq(&self, other: &Decimal<DIGITS>) -> bool {
        *self * Decimal::<DIGITS>::SCALE_INT == other.0
    }
}

impl<const DIGITS: u8> PartialEq<Decimal<DIGITS>> for f64 {
    #[inline]
    fn eq(&self, other: &Decimal<DIGITS>) -> bool {
        *self * Decimal::<DIGITS>::SCALE_F64 == other.0 as f64
    }
}

impl<const DIGITS: u8> From<i32> for Decimal<DIGITS> {
    #[inline]
    fn from(item: i32) -> Self {
        Decimal::<DIGITS>(item as i64 * Self::SCALE_INT)
    }
}

impl<const DIGITS: u8> From<i64> for Decimal<DIGITS> {
    #[inline]
    fn from(item: i64) -> Self {
        Decimal::<DIGITS>(item * Self::SCALE_INT)
    }
}

impl<const DIGITS: u8> From<f64> for Decimal<DIGITS> {
    #[inline]
    fn from(item: f64) -> Self {
        if (item < Self::F64_MAX) && (item > Self::F64_MIN) {
            Decimal::<DIGITS>((item * Self::SCALE_F64) as i64)
        } else if item < Self::F64_MIN {
            Self::MIN
        } else {
            Self::MAX
        }
    }
}

impl<const DIGITS: u8> From<f32> for Decimal<DIGITS> {
    #[inline]
    fn from(item: f32) -> Self {
        Self::from(item as f64)
    }
}

impl<const DIGITS: u8> Neg for Decimal<DIGITS> {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self::Output {
        Decimal::<DIGITS>(-self.0)
    }
}

impl<const DIGITS: u8> Add for Decimal<DIGITS> {
    type Output = Self;
    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        Decimal::<DIGITS>(self.0 + rhs.0)
    }
}

impl<const DIGITS: u8> Add<i64> for Decimal<DIGITS> {
    type Output = Self;
    #[inline]
    fn add(self, other: i64) -> Self {
        Decimal::<DIGITS>(self.0 + other * Self::SCALE_INT)
    }
}

impl<const DIGITS: u8> Add<f64> for Decimal<DIGITS> {
    type Output = Self;
    #[inline]
    fn add(self, other: f64) -> Self {
        Decimal::<DIGITS>(self.0 + (other * Self::SCALE_F64) as i64)
    }
}

impl<const DIGITS: u8> Add<i32> for Decimal<DIGITS> {
    type Output = Self;
    #[inline]
    fn add(self, rhs: i32) -> Self {
        Decimal::<DIGITS>(self.0 + (rhs as i64) * Self::SCALE_INT)
    }
}

impl<const DIGITS: u8> Add<Decimal<DIGITS>> for i64 {
    type Output = Self;
    #[allow(clippy::suspicious_arithmetic_impl)]
    #[inline]
    fn add(self, other: Decimal<DIGITS>) -> Self {
        let mut quo = other.0 / Decimal::<DIGITS>::SCALE_INT;
        let rem = other.0 % Decimal::<DIGITS>::SCALE_INT;
        if rem >= Decimal::<DIGITS>::SCALE_INT_HALF {
            quo += 1; // make sure works for negative
        } else if rem <= -Decimal::<DIGITS>::SCALE_INT_HALF {
            quo -= 1;
        }
        self + quo
    }
}

impl<const DIGITS: u8> Add<Decimal<DIGITS>> for f64 {
    type Output = Self;
    #[inline]
    fn add(self, other: Decimal<DIGITS>) -> Self {
        self + other.to_f64()
    }
}

impl<const DIGITS: u8> Sub for Decimal<DIGITS> {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: Self) -> Self {
        Decimal::<DIGITS>(self.0 - rhs.0)
    }
}

impl<const DIGITS: u8> Sub<i64> for Decimal<DIGITS> {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: i64) -> Self {
        Decimal::<DIGITS>(self.0 - rhs * Self::SCALE_INT)
    }
}

impl<const DIGITS: u8> Sub<i32> for Decimal<DIGITS> {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: i32) -> Self {
        Decimal::<DIGITS>(self.0 - (rhs as i64) * Self::SCALE_INT)
    }
}

impl<const DIGITS: u8> Sub<f64> for Decimal<DIGITS> {
    type Output = Self;
    #[inline]
    fn sub(self, other: f64) -> Self {
        Decimal::<DIGITS>(self.0 - (other * Self::SCALE_F64) as i64)
    }
}

impl<const DIGITS: u8> Sub<Decimal<DIGITS>> for i64 {
    type Output = Self;
    #[allow(clippy::suspicious_arithmetic_impl)]
    #[inline]
    fn sub(self, other: Decimal<DIGITS>) -> Self {
        let mut quo = other.0 / Decimal::<DIGITS>::SCALE_INT;
        let rem = other.0 % Decimal::<DIGITS>::SCALE_INT;
        if rem >= Decimal::<DIGITS>::SCALE_INT_HALF {
            quo += 1; // make sure works for negative
        } else if rem <= -Decimal::<DIGITS>::SCALE_INT_HALF {
            quo -= 1;
        }
        self - quo
    }
}

impl<const DIGITS: u8> Sub<Decimal<DIGITS>> for f64 {
    type Output = Self;
    #[inline]
    fn sub(self, other: Decimal<DIGITS>) -> Self {
        self - other.to_f64()
    }
}

impl<const DIGITS: u8> Mul for Decimal<DIGITS> {
    type Output = Self;

    #[inline]
    fn mul(self, rhs: Decimal<DIGITS>) -> Self::Output {
        self.mul_rounded(rhs, Rounding::HalfUp)
    }
}

impl<const DIGITS: u8> Mul<i64> for Decimal<DIGITS> {
    type Output = Decimal<DIGITS>;

    #[inline]
    fn mul(self, rhs: i64) -> Decimal<DIGITS> {
        Decimal::<DIGITS>(self.0 * rhs)
    }
}

impl<const DIGITS: u8> Mul<i32> for Decimal<DIGITS> {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: i32) -> Self {
        Decimal::<DIGITS>(self.0 * (rhs as i64))
    }
}

impl<const DIGITS: u8> Mul<Decimal<DIGITS>> for i64 {
    type Output = i64;

    #[inline]
    fn mul(self, rhs: Decimal<DIGITS>) -> i64 {
        (Decimal::<DIGITS>(self) * rhs).0
    }
}

impl<const DIGITS: u8> Div for Decimal<DIGITS> {
    type Output = Self;

    #[inline]
    fn div(self, rhs: Self) -> Self {
        self.div_rounded(rhs, Rounding::HalfUp)
    }
}

impl<const DIGITS: u8> Rem for Decimal<DIGITS> {
    type Output = Self;

    /// # Panics
    /// Panics if `rhs` is zero;
    /// [`checked_rem`](Decimal::checked_rem) is the non-panicking form.
    #[inline]
    fn rem(self, rhs: Self) -> Self {
        match self.checked_rem(rhs) {
            Some(v) => v,
            None => panic!("attempt to calculate the remainder with a divisor of zero"),
        }
    }
}

crate::common::impl_decimal_common!(Decimal, "Decimal");

#[cfg(test)]
mod tests {
    extern crate std;
    use crate::Amount64;
    use crate::AmountErrorKind;
    use crate::Decimal;
    use crate::Rate64;
    use crate::Rounding;
    use core::str::FromStr;
    use std::format;

    #[test]
    fn test_decimal_parts_roundtrip() {
        // mantissa() / to_decimal_parts() expose the raw scaled value.
        let a = Amount64::from(3);
        assert_eq!(a.mantissa(), 30000);
        assert_eq!(a.to_decimal_parts(), (30000, -4));
        assert_eq!(Amount64::SCALE, 4);
        assert_eq!(Decimal::<8>::SCALE, 8);
        assert_eq!(Decimal::<0>::SCALE, 0);

        // Round-trip through (mantissa, exponent) for several values.
        for raw in [0i64, 1, -1, 12345, -98765, i64::MAX, -i64::MAX] {
            let d = Decimal::<4>(raw);
            let (m, e) = d.to_decimal_parts();
            assert_eq!(Amount64::from_decimal_parts(m, e), Ok(d));
        }
    }

    #[test]
    fn test_from_decimal_parts_scaling() {
        // Scale up: 1.23 == 123 * 10^-2 retargeted to 4 digits == 12300.
        assert_eq!(
            Amount64::from_decimal_parts(123, -2),
            Ok(Decimal::<4>(12300))
        );
        // Exponent equal to scale: integer scaling.
        assert_eq!(Amount64::from_decimal_parts(7, 0), Ok(Decimal::<4>(70000)));
        // Positive exponent scales further up.
        assert_eq!(
            Amount64::from_decimal_parts(5, 2),
            Ok(Decimal::<4>(5_000_000))
        );
        // Zero with any exponent is always representable.
        assert_eq!(Amount64::from_decimal_parts(0, -100), Ok(Decimal::<4>(0)));
        assert_eq!(Amount64::from_decimal_parts(0, 100), Ok(Decimal::<4>(0)));

        // Exact scale-down: surplus trailing zeros are droppable.
        // 1230000 * 10^-6 == 1.23 == 12300 * 10^-4.
        assert_eq!(
            Amount64::from_decimal_parts(1_230_000, -6),
            Ok(Decimal::<4>(12300))
        );
    }

    #[test]
    fn test_from_decimal_parts_inexact() {
        // More fractional digits than a 4-digit type can hold.
        assert_eq!(
            Amount64::from_decimal_parts(1, -5),
            Err(AmountErrorKind::Inexact)
        );
        assert_eq!(
            Amount64::from_decimal_parts(12345, -5),
            Err(AmountErrorKind::Inexact)
        );
        // Huge negative exponent with non-zero mantissa: inexact, not a panic.
        assert_eq!(
            Amount64::from_decimal_parts(1, -1000),
            Err(AmountErrorKind::Inexact)
        );

        // Trailing zeros after the representable digits are NOT inexact: the
        // dropped digits are all zero, so the value is exact.
        assert_eq!(
            Amount64::from_decimal_parts(12300, -5),
            Ok(Decimal::<4>(1230)) // 0.12300 -> 0.1230
        );
        assert_eq!(
            Amount64::from_decimal_parts(120_000, -5),
            Ok(Decimal::<4>(12000)) // 1.20000 -> 1.2000
        );
        // Many surplus zeros are still exact.
        assert_eq!(
            Amount64::from_decimal_parts(50_000_000, -10),
            Ok(Decimal::<4>(50)) // 0.0050000000 -> 0.0050
        );
    }

    #[test]
    fn test_from_decimal_parts_rounded() {
        use crate::Rounding::*;
        // 1.23456 -> 4 digits. Round digit is 6 (> half).
        for mode in [HalfEven, HalfUp, HalfDown, Up] {
            assert_eq!(
                Amount64::from_decimal_parts_rounded(123456, -5, mode),
                Ok(Decimal::<4>(12346))
            );
        }
        assert_eq!(
            Amount64::from_decimal_parts_rounded(123456, -5, Down),
            Ok(Decimal::<4>(12345))
        );

        // Exact half: 1.23455 -> last kept digit decides HalfEven/HalfDown.
        assert_eq!(
            Amount64::from_decimal_parts_rounded(123455, -5, HalfUp),
            Ok(Decimal::<4>(12346))
        );
        assert_eq!(
            Amount64::from_decimal_parts_rounded(123455, -5, HalfDown),
            Ok(Decimal::<4>(12345))
        );
        assert_eq!(
            Amount64::from_decimal_parts_rounded(123455, -5, HalfEven),
            Ok(Decimal::<4>(12346)) // 12345 is odd -> round to even 12346
        );
        assert_eq!(
            Amount64::from_decimal_parts_rounded(123465, -5, HalfEven),
            Ok(Decimal::<4>(12346)) // 12346 is even -> stays
        );

        // Negative values round away from / toward zero symmetrically.
        assert_eq!(
            Amount64::from_decimal_parts_rounded(-123456, -5, HalfUp),
            Ok(Decimal::<4>(-12346))
        );
        assert_eq!(
            Amount64::from_decimal_parts_rounded(-123456, -5, Down),
            Ok(Decimal::<4>(-12345))
        );
        assert_eq!(
            Amount64::from_decimal_parts_rounded(-123451, -5, Up),
            Ok(Decimal::<4>(-12346))
        );

        // Exact inputs are unaffected by the mode.
        assert_eq!(
            Amount64::from_decimal_parts_rounded(1_230_000, -6, Down),
            Ok(Decimal::<4>(12300))
        );

        // Magnitude below half a ULP: rounds to zero, except `Up`.
        assert_eq!(
            Amount64::from_decimal_parts_rounded(1, -1000, HalfUp),
            Ok(Decimal::<4>(0))
        );
        assert_eq!(
            Amount64::from_decimal_parts_rounded(1, -1000, Up),
            Ok(Decimal::<4>(1))
        );
        assert_eq!(
            Amount64::from_decimal_parts_rounded(-1, -1000, Up),
            Ok(Decimal::<4>(-1))
        );

        // Overflow still reported when the rounded value won't fit.
        assert_eq!(
            Amount64::from_decimal_parts_rounded(i128::MAX, 0, HalfUp),
            Err(AmountErrorKind::Overflow)
        );
    }

    #[test]
    fn test_parse_rounded() {
        use crate::Rounding::*;
        use crate::parse_decimal_i64_rounded;

        // Default parse / FromStr keep HalfUp behavior.
        assert_eq!(Amount64::from_str("1.23455"), Ok(Decimal::<4>(12346)));

        // HalfEven uses the sticky bit and parity of the kept digit.
        assert_eq!(parse_decimal_i64_rounded("1.23455", 4, HalfEven), Ok(12346));
        assert_eq!(parse_decimal_i64_rounded("1.23465", 4, HalfEven), Ok(12346));
        // 1.234551 is past the half -> always up regardless of parity.
        assert_eq!(
            parse_decimal_i64_rounded("1.234551", 4, HalfEven),
            Ok(12346)
        );
        // HalfDown drops an exact half but rounds 5-with-remainder up.
        assert_eq!(parse_decimal_i64_rounded("1.23455", 4, HalfDown), Ok(12345));
        assert_eq!(
            parse_decimal_i64_rounded("1.234551", 4, HalfDown),
            Ok(12346)
        );

        // Trailing zeros never change the value or carry into rounding.
        assert_eq!(parse_decimal_i64_rounded("1.23450000", 4, Up), Ok(12345));
        assert_eq!(parse_decimal_i64_rounded("1.2345", 4, Up), Ok(12345));
        // Any non-zero dropped digit rounds away from zero under `Up`.
        assert_eq!(parse_decimal_i64_rounded("1.23451", 4, Up), Ok(12346));
        assert_eq!(parse_decimal_i64_rounded("-1.23451", 4, Up), Ok(-12346));
        assert_eq!(parse_decimal_i64_rounded("1.23459", 4, Down), Ok(12345));

        // Rounding can carry into the integer part.
        assert_eq!(parse_decimal_i64_rounded("0.99995", 4, HalfUp), Ok(10000));
    }

    #[test]
    fn test_from_decimal_parts_overflow() {
        // Scaled value exceeds the i64 backing.
        assert_eq!(
            Amount64::from_decimal_parts(i128::MAX, 0),
            Err(AmountErrorKind::Overflow)
        );
        // Power of ten itself overflows i128.
        assert_eq!(
            Amount64::from_decimal_parts(1, 1000),
            Err(AmountErrorKind::Overflow)
        );
        // Just past the backing range.
        assert_eq!(
            Amount64::from_decimal_parts(i64::MAX as i128 + 1, -4),
            Err(AmountErrorKind::Overflow)
        );
    }

    #[test]
    fn test_add() {
        assert_eq!(
            Decimal::<4>(10000) + Decimal::<4>(20000),
            Decimal::<4>(30000)
        );
        assert_eq!(
            Decimal::<4>(10000) + Decimal::<4>(20001),
            Decimal::<4>(30001)
        );
        assert_eq!(
            Decimal::<4>(10000) + Decimal::<4>(-20000),
            Decimal::<4>(-10000)
        );
        assert_eq!(
            Decimal::<4>(9223372036854775806) + Decimal::<4>(1),
            Decimal::<4>(9223372036854775807)
        );
    }

    #[test]
    fn test_trunc() {
        assert_eq!(Decimal::<4>(10000).trunc(), Decimal::<4>(10000));
        assert_eq!(Decimal::<4>(10001).trunc(), Decimal::<4>(10000));
        assert_eq!(Decimal::<4>(19999).trunc(), Decimal::<4>(10000));
        assert_eq!(Decimal::<4>(199999).trunc(), Decimal::<4>(190000));

        assert_eq!(Decimal::<4>(-10000).trunc(), Decimal::<4>(-10000));
        assert_eq!(Decimal::<4>(-10001).trunc(), Decimal::<4>(-10000));
        assert_eq!(Decimal::<4>(-19999).trunc(), Decimal::<4>(-10000));
        assert_eq!(Decimal::<4>(-199999).trunc(), Decimal::<4>(-190000));
    }

    #[test]
    fn test_floor() {
        assert_eq!(Decimal::<4>(10000).floor(), Decimal::<4>(10000));
        assert_eq!(Decimal::<4>(10001).floor(), Decimal::<4>(10000));
        assert_eq!(Decimal::<4>(19999).floor(), Decimal::<4>(10000));
        assert_eq!(Decimal::<4>(199999).floor(), Decimal::<4>(190000));

        assert_eq!(Decimal::<4>(-10000).floor(), Decimal::<4>(-10000));
        assert_eq!(Decimal::<4>(-10001).floor(), Decimal::<4>(-20000));
        assert_eq!(Decimal::<4>(-19999).floor(), Decimal::<4>(-20000));
        assert_eq!(Decimal::<4>(-199999).floor(), Decimal::<4>(-200000));
    }

    #[test]
    fn test_round() {
        assert_eq!(Decimal::<4>(10000).round(), Decimal::<4>(10000));
        assert_eq!(Decimal::<4>(10001).round(), Decimal::<4>(10000));
        assert_eq!(Decimal::<4>(19999).round(), Decimal::<4>(20000));
        assert_eq!(Decimal::<4>(199999).round(), Decimal::<4>(200000));

        assert_eq!(Decimal::<4>(-10000).round(), Decimal::<4>(-10000));
        assert_eq!(Decimal::<4>(-10001).round(), Decimal::<4>(-10000));
        assert_eq!(Decimal::<4>(-19999).round(), Decimal::<4>(-20000));
        assert_eq!(Decimal::<4>(-199999).round(), Decimal::<4>(-200000));
    }

    #[test]
    fn test_round100() {
        assert_eq!(Decimal::<4>(10000).round100(), Decimal::<4>(10000));
        assert_eq!(Decimal::<4>(10001).round100(), Decimal::<4>(10000));
        assert_eq!(Decimal::<4>(19999).round100(), Decimal::<4>(20000));
        assert_eq!(Decimal::<4>(199999).round100(), Decimal::<4>(200000));

        assert_eq!(Decimal::<4>(-10000).round100(), Decimal::<4>(-10000));
        assert_eq!(Decimal::<4>(-10001).round100(), Decimal::<4>(-10000));
        assert_eq!(Decimal::<4>(-19999).round100(), Decimal::<4>(-20000));
        assert_eq!(Decimal::<4>(-199999).round100(), Decimal::<4>(-200000));

        assert_eq!(Decimal::<4>(-10050).round100(), Decimal::<4>(-10100));
        assert_eq!(Decimal::<4>(10050).round100(), Decimal::<4>(10100));

        assert_eq!(Decimal::<4>(10049).round100(), Decimal::<4>(10000));
    }

    #[test]
    fn test_sub() {
        assert_eq!(
            Decimal::<4>(10000) - Decimal::<4>(20000),
            Decimal::<4>(-10000)
        );
        assert_eq!(
            Decimal::<4>(10000) - Decimal::<4>(20001),
            Decimal::<4>(-10001)
        );
        assert_eq!(
            Decimal::<4>(10000) - Decimal::<4>(-20000),
            Decimal::<4>(30000)
        );
        assert_eq!(
            Decimal::<4>(9223372036854775807) - Decimal::<4>(1),
            Decimal::<4>(9223372036854775806)
        );
    }

    // test operations with integers
    #[test]
    fn test_add_int() {
        assert_eq!(Decimal::<4>(10000) + 2, Decimal::<4>(30000));
        assert_eq!(Decimal::<4>(10001) + 2, Decimal::<4>(30001));
        assert_eq!(Decimal::<4>(10000) + (-2), Decimal::<4>(-10000));
        assert_eq!(
            Decimal::<4>(9223372036854765806) + 1,
            Decimal::<4>(9223372036854775806)
        );
    }

    // test multiplication of scaled
    #[test]
    fn test_mul() {
        assert_eq!(
            Decimal::<4>(10000) * Decimal::<4>(10000),
            Decimal::<4>(10000)
        );
        assert_eq!(
            Decimal::<4>(10000) * Decimal::<4>(-11111),
            Decimal::<4>(-11111)
        );
        assert_eq!(
            Decimal::<4>(10001) * Decimal::<4>(10001),
            Decimal::<4>(10002)
        );
        assert_eq!(
            Decimal::<4>(9223372036854775807) * Decimal::<4>(10000),
            Decimal::<4>(9223372036854775807)
        );
        assert_eq!(
            Decimal::<4>(11004) * Decimal::<4>(10015),
            Decimal::<4>(11021)
        );
        assert_eq!(
            Decimal::<4>(11004) * Decimal::<4>(-10015),
            Decimal::<4>(-11021)
        );
    }

    #[test]
    fn test_div() {
        assert_eq!(
            Decimal::<4>(10000) / Decimal::<4>(10000),
            Decimal::<4>(10000)
        );
        assert_eq!(
            Decimal::<4>(10000) / Decimal::<4>(20000),
            Decimal::<4>(5000)
        );
        assert_eq!(
            Decimal::<4>(10000) / Decimal::<4>(5000),
            Decimal::<4>(20000)
        );

        assert_eq!(
            Decimal::<4>(10001) / Decimal::<4>(10001),
            Decimal::<4>(10000)
        );
        assert_eq!(
            Decimal::<4>(9223372036854775807) / Decimal::<4>(10000),
            Decimal::<4>(9223372036854775807)
        );

        assert_eq!(
            Decimal::<4>(10000) / Decimal::<4>(110000),
            Decimal::<4>(909)
        );
        assert_eq!(
            Decimal::<4>(10000) / Decimal::<4>(110000),
            Decimal::<4>(909)
        );

        // test roundings to be 'decimal'
        assert_eq!(
            Decimal::<4>(10000) / Decimal::<4>(130000),
            Decimal::<4>(769)
        );
        assert_eq!(
            Decimal::<4>(10000) / Decimal::<4>(-130000),
            Decimal::<4>(-769)
        );
        assert_eq!(
            Decimal::<4>(-10000) / Decimal::<4>(-130000),
            Decimal::<4>(769)
        );
        assert_eq!(
            Decimal::<4>(-10000) / Decimal::<4>(130000),
            Decimal::<4>(-769)
        );

        assert_eq!(
            Decimal::<4>(10000) / Decimal::<4>(180000),
            Decimal::<4>(556)
        );
        assert_eq!(
            Decimal::<4>(10000) / Decimal::<4>(-180000),
            Decimal::<4>(-556)
        );
        assert_eq!(
            Decimal::<4>(-10000) / Decimal::<4>(180000),
            Decimal::<4>(-556)
        );
        assert_eq!(
            Decimal::<4>(-10000) / Decimal::<4>(-180000),
            Decimal::<4>(556)
        );
    }

    #[test]
    fn test_recip() {
        assert_eq!(Decimal::<4>(10000).recip(), Decimal::<4>(10000));
        assert_eq!(Decimal::<4>(9223372036854775807).recip(), Decimal::<4>(0));

        assert_eq!(Decimal::<4>(110000).recip(), Decimal::<4>(909));
        assert_eq!(Decimal::<4>(-110000).recip(), Decimal::<4>(-909));

        // test roundings to be 'decimal'
        assert_eq!(Decimal::<4>(130000).recip(), Decimal::<4>(769));
        assert_eq!(Decimal::<4>(-130000).recip(), Decimal::<4>(-769));

        assert_eq!(Decimal::<4>(180000).recip(), Decimal::<4>(556));
        assert_eq!(Decimal::<4>(-180000).recip(), Decimal::<4>(-556));
    }

    #[test]
    fn test_misc() {
        let a = Amount64::from_f32(1.0).unwrap();
        let b = Amount64::from_f32(0.5).unwrap();
        assert_eq!(a.0, 10000);
        assert_eq!(b.0, 5000);

        let c = a / b;
        assert_eq!(c.0, 20000);
        let d = a * b;
        assert_eq!(d.0, 5000);
        let e = b - 1i64;
        assert_eq!(e.0, -5000);
    }
    #[test]
    fn test_from_str() {
        assert_eq!(Amount64::from_str(""), Err(AmountErrorKind::Empty));
        assert_eq!(Amount64::from_str("+"), Err(AmountErrorKind::Empty));
        assert_eq!(Amount64::from_str("-"), Err(AmountErrorKind::Empty));
        assert_eq!(Amount64::from_str("-."), Err(AmountErrorKind::Empty));
        assert_eq!(Amount64::from_str("+."), Err(AmountErrorKind::Empty));
        assert_eq!(Amount64::from_str("-+"), Err(AmountErrorKind::InvalidDigit));

        assert_eq!(Amount64::from_str("1").unwrap().0, 10000);
        assert_eq!(Amount64::from_str("+1").unwrap().0, 10000);
        assert_eq!(Amount64::from_str("1.").unwrap().0, 10000);
        assert_eq!(Amount64::from_str("1.0").unwrap().0, 10000);
        assert_eq!(Amount64::from_str("+1.0").unwrap().0, 10000);
        assert_eq!(Amount64::from_str("1.00").unwrap().0, 10000);
        assert_eq!(Amount64::from_str("1.000").unwrap().0, 10000);
        assert_eq!(Amount64::from_str("1.0000").unwrap().0, 10000);
        assert_eq!(Amount64::from_str("1.00000").unwrap().0, 10000);
        assert_eq!(Amount64::from_str("01.00000").unwrap().0, 10000);
        assert_eq!(Amount64::from_str("-1").unwrap().0, -10000);
        assert_eq!(Amount64::from_str("-1.").unwrap().0, -10000);
        assert_eq!(Amount64::from_str("-1.0").unwrap().0, -10000);
        assert_eq!(Amount64::from_str("-1.00").unwrap().0, -10000);
        assert_eq!(Amount64::from_str("-1.000").unwrap().0, -10000);
        assert_eq!(Amount64::from_str("-1.0000").unwrap().0, -10000);
        assert_eq!(Amount64::from_str("-1.00000").unwrap().0, -10000);
        assert_eq!(Amount64::from_str("-01.00000").unwrap().0, -10000);
        assert_eq!(Amount64::from_str("1.5").unwrap().0, 15000);
        assert_eq!(Amount64::from_str("1.05").unwrap().0, 10500);
        assert_eq!(Amount64::from_str("1.005").unwrap().0, 10050);
        assert_eq!(Amount64::from_str("1.0005").unwrap().0, 10005);
        assert_eq!(Amount64::from_str("1.00005").unwrap().0, 10001);
        assert_eq!(Amount64::from_str("1.00004").unwrap().0, 10000);
        assert_eq!(Amount64::from_str("1.00006").unwrap().0, 10001);
        assert_eq!(
            Amount64::from_str("922337203685477.5807").unwrap().0,
            9223372036854775807
        );
        assert_eq!(
            Amount64::from_str("-922337203685477.5807").unwrap().0,
            -9223372036854775807
        );
        assert_eq!(
            Amount64::from_str("922337203685477.5808"),
            Err(AmountErrorKind::Overflow)
        );
        assert_eq!(
            Amount64::from_str("-922337203685477.5808"),
            Err(AmountErrorKind::Overflow)
        );
    }
    #[test]
    fn test_display() {
        assert_eq!(&format!("{}", Decimal::<4>(10000)), "1");
        assert_eq!(&format!("{:+}", Decimal::<4>(10000)), "+1");
        assert_eq!(&format!("{:2}", Decimal::<4>(10000)), " 1");
        assert_eq!(&format!("{:3}", Decimal::<4>(10000)), "  1");
        assert_eq!(&format!("{:4.2}", Decimal::<4>(10000)), "1.00");
        assert_eq!(&format!("{:T>4.2}", Decimal::<4>(10000)), "1.00");
        assert_eq!(&format!("{:<3}", Decimal::<4>(10000)), "1  ");
        assert_eq!(&format!("{:03}", Decimal::<4>(10000)), "001");
        assert_eq!(&format!("{:+2}", Decimal::<4>(10000)), "+1");
        assert_eq!(&format!("{:+05}", Decimal::<4>(10000)), "+0001");
        assert_eq!(&format!("{}", Decimal::<4>(1)), "0.0001");
        assert_eq!(&format!("{}", Decimal::<4>(10)), "0.001");
        assert_eq!(&format!("{}", Decimal::<4>(-10000)), "-1");
        assert_eq!(&format!("{:+}", Decimal::<4>(-10000)), "-1");
        assert_eq!(&format!("{}", Decimal::<4>(10001)), "1.0001");
        assert_eq!(&format!("{}", Decimal::<4>(-10001)), "-1.0001");
        // Regression: zero used to render as "-0" (pad_integral was handed
        // `num > 0` as the non-negative flag).
        assert_eq!(&format!("{}", Decimal::<4>(0)), "0");
        assert_eq!(&format!("{:+}", Decimal::<4>(0)), "+0"); // matches i32 behavior
    }

    #[test]
    fn test_rate64() {
        use crate::Rate64;
        let rate = Rate64::from(1.12345678);
        assert_eq!(&format!("{}", rate), "1.12345678");
        assert_eq!(rate.0, 112345678);
    }

    #[test]
    fn test_rounding_modes() {
        use crate::Rounding;
        let a = Amount64::from(1.5);
        assert_eq!(a.round_to(Rounding::HalfUp), Amount64::from(2));
        assert_eq!(a.round_to(Rounding::HalfDown), Amount64::from(1));
        assert_eq!(a.round_to(Rounding::HalfEven), Amount64::from(2));
        assert_eq!(a.round_to(Rounding::Down), Amount64::from(1));
        assert_eq!(a.round_to(Rounding::Up), Amount64::from(2));
    }

    #[test]
    fn test_checked_math() {
        let max = Amount64::MAX;
        assert_eq!(max.checked_add(Amount64::from(1)), None);
        assert_eq!(
            Amount64::from(2).checked_sub(Amount64::from(1)),
            Some(Amount64::from(1))
        );
        assert_eq!(Amount64::from(2).checked_div(Amount64::from(0)), None);
        // Regression: checked_div used to return the remainder, not the quotient.
        assert_eq!(
            Amount64::from(6).checked_div(Amount64::from(2)),
            Some(Amount64::from(3))
        );
        assert_eq!(
            Amount64::from(1).checked_div(Amount64::from(3)),
            Some(Decimal::<4>(3333))
        );
        assert_eq!(
            Amount64::from(-1).checked_div(Amount64::from(3)),
            Some(Decimal::<4>(-3333))
        );
        assert_eq!(max.checked_mul(Amount64::from(2)), None);
    }

    #[test]
    fn test_const_eval() {
        use crate::Rounding;
        // Whole expressions evaluate at compile time.
        const PRICE: Amount64 = Amount64::from_str_const("19.99");
        const RATE: Amount64 = Amount64::from_str_const("0.0825");
        const TAX: Amount64 = PRICE.mul_rounded(RATE, Rounding::HalfEven);
        const DOUBLED: Option<Amount64> = PRICE.checked_mul(Amount64::from_str_const("2"));
        const GROWTH: Amount64 = Amount64::from_str_const("1.05").powi(10);
        const ROUNDED: Amount64 = TAX.round_to(Rounding::HalfUp);
        // ceil/floor/round are const via round_to; pin the negative-operand
        // ceiling (truncation toward +inf) under CTFE.
        const CEIL_NEG: Amount64 = Amount64::from_str_const("-3.25").ceil();
        const FLOOR_NEG: Amount64 = Amount64::from_str_const("-3.25").floor();
        // The checked forms are const too; overflow yields None under CTFE
        // instead of a compile error.
        const REM: Option<Amount64> = PRICE.checked_rem(Amount64::from_str_const("3"));
        const POW_OVER: Option<Amount64> = Amount64::MAX.checked_powi(2);
        const RND_OVER: Option<Amount64> = Amount64::MAX.checked_round_to(Rounding::Up);
        const RDP: Amount64 = Amount64::from_str_const("12.3456").round_dp(2, Rounding::HalfUp);
        const EVEN: Option<crate::EvenSplit<Amount64>> =
            Amount64::from_str_const("100.00").checked_split_evenly(3);
        // Cross-scale multiply (4-digit amount x 8-digit rate) and integer
        // division both evaluate at compile time.
        const FEE: Amount64 = PRICE.mul_rounded(Rate64::from_str_const("0.0725"), Rounding::HalfUp);
        const SPLIT: Amount64 =
            Amount64::from_str_const("100.0001").div_int_rounded(3, Rounding::HalfUp);
        // Square roots evaluate at compile time too.
        const ROOT2: Amount64 = Amount64::from_str_const("2").sqrt();

        assert_eq!(PRICE.0, 199_900);
        // Compile-time results match the runtime paths exactly.
        let price = Amount64::from_str("19.99").unwrap();
        let rate = Amount64::from_str("0.0825").unwrap();
        assert_eq!(TAX, price.mul_rounded(rate, Rounding::HalfEven));
        assert_eq!(DOUBLED, price.checked_mul(Amount64::from(2)));
        assert_eq!(GROWTH, Amount64::from_str("1.05").unwrap().powi(10));
        assert_eq!(ROUNDED, TAX.round_to(Rounding::HalfUp));
        assert_eq!(CEIL_NEG, Amount64::from(-3));
        assert_eq!(FLOOR_NEG, Amount64::from(-4));
        assert_eq!(REM, Some(Amount64::from_str_const("1.99")));
        assert_eq!(POW_OVER, None);
        assert_eq!(RND_OVER, None);
        assert_eq!(RDP, Amount64::from_str_const("12.35"));
        assert_eq!(EVEN.unwrap().high, Amount64::from_str_const("33.3334"));
        assert_eq!(
            FEE,
            price.mul_rounded(Rate64::from_str("0.0725").unwrap(), Rounding::HalfUp)
        );
        assert_eq!(SPLIT, Amount64::from_str("33.3334").unwrap());
        assert_eq!(ROOT2, Amount64::from(2).sqrt());
        assert_eq!(ROOT2.0, 14142);
        assert_eq!(
            Amount64::from_str_rounded("1.00005", Rounding::HalfEven),
            Ok(Decimal::<4>(10000))
        );

        // Const-evaluable accessors and conversions (CTFE runs with overflow
        // checks always on); the runtime asserts pin the same values.
        const N: Amount64 = Amount64::from_str_const("2.5");
        const ABS: Amount64 = Amount64::from_str_const("-2.5").abs();
        const FRACT: Amount64 = N.fract();
        const BITS: u64 = N.to_bits();
        const FROM_BITS: Amount64 = Amount64::from_bits(25_000);
        const SUM: Option<Amount64> = N.checked_add(N);
        const FROM_INT: Result<Amount64, AmountErrorKind> = Amount64::from_i64(2);
        const PARTS: Result<Amount64, AmountErrorKind> =
            Amount64::from_decimal_parts_rounded(25, -1, Rounding::HalfUp);
        const INT: i64 = N.to_i64();
        assert_eq!(N, Decimal::<4>(25_000));
        assert_eq!(ABS, N);
        assert_eq!(FRACT, Decimal::<4>(5000));
        assert_eq!(BITS, 25_000);
        assert_eq!(FROM_BITS, N);
        assert_eq!(SUM, Some(Amount64::from(5)));
        assert_eq!(FROM_INT, Ok(Amount64::from(2)));
        assert_eq!(PARTS, Ok(N));
        assert_eq!(INT, 2);
    }

    #[test]
    fn test_div_half_ties() {
        // Exact half ties round away from zero under the default HalfUp:
        // 0.0001 / 2 = 0.00005 -> 0.0001.
        assert_eq!(Decimal::<4>(1) / Decimal::<4>(20000), Decimal::<4>(1));
        assert_eq!(Decimal::<4>(-1) / Decimal::<4>(20000), Decimal::<4>(-1));
        assert_eq!(
            Decimal::<4>(1).checked_div(Decimal::<4>(20000)),
            Some(Decimal::<4>(1))
        );
        // recip: 1 / 20000.0 = 0.00005 -> 0.0001.
        assert_eq!(Decimal::<4>(200000000).recip(), Decimal::<4>(1));

        // HalfEven with an odd divisor: rem == (d-1)/2 is *below* the half,
        // so 0.0001 / 0.0003 = 0.3333... stays 0.3333.
        use crate::Rounding;
        assert_eq!(
            Decimal::<4>(1).div_rounded(Decimal::<4>(3), Rounding::HalfEven),
            Decimal::<4>(3333)
        );
        // Even divisor exact tie obeys the parity of the quotient.
        // 0.3333 / 2 = 0.16665: quotient 1666 is even -> stays.
        assert_eq!(
            Decimal::<4>(3333).div_rounded(Decimal::<4>(20000), Rounding::HalfEven),
            Decimal::<4>(1666)
        );
        // 0.3335 / 2 = 0.16675: quotient 1667 is odd -> rounds to 1668.
        assert_eq!(
            Decimal::<4>(3335).div_rounded(Decimal::<4>(20000), Rounding::HalfEven),
            Decimal::<4>(1668)
        );
    }

    #[test]
    fn test_mul_rounded_cross_scale() {
        use crate::Rounding::*;
        // Amount (4 digits) x Rate (8 digits) rounds once to the amount's scale.
        let amount = Amount64::from_str("125.00").unwrap();
        let rate = Rate64::from_str("0.0725").unwrap();
        assert_eq!(
            amount.mul_rounded(rate, HalfUp),
            Amount64::from_str("9.0625").unwrap()
        );
        // Checked form: overflow becomes None instead of a panic.
        assert_eq!(
            Amount64::MAX.checked_mul_rounded(Amount64::from(2), HalfUp),
            None
        );
        assert_eq!(
            amount.checked_mul_rounded(rate, HalfUp),
            Some(amount.mul_rounded(rate, HalfUp))
        );
        // 1.0000 * 0.00005 = 0.00005: a tie at the 4-digit scale.
        let tie = Rate64::from_str("0.00005").unwrap();
        assert_eq!(Amount64::from(1).mul_rounded(tie, HalfUp).0, 1);
        assert_eq!(Amount64::from(1).mul_rounded(tie, HalfEven).0, 0);
        assert_eq!(Amount64::from(1).mul_rounded(tie, Down).0, 0);
        assert_eq!(Amount64::from(-1).mul_rounded(tie, HalfUp).0, -1);
        assert_eq!(Amount64::from(-1).mul_rounded(tie, Down).0, -1);
        assert_eq!(Amount64::from(-1).mul_rounded(tie, Up).0, 0);
    }

    #[test]
    fn test_div_rounded_to() {
        use crate::Rounding::*;
        // The quotient of two 4-digit amounts taken directly at 8 digits.
        let two = Amount64::from(2);
        let three = Amount64::from(3);
        assert_eq!(two.div_rounded_to::<8>(three, HalfUp).0, 66_666_667);
        assert_eq!(two.div_rounded_to::<8>(three, Down).0, 66_666_666);
        assert_eq!((-two).div_rounded_to::<8>(three, Down).0, -66_666_667);
        // Same target scale degenerates to div_rounded.
        for mode in [HalfUp, HalfDown, HalfEven, Down, Up] {
            assert_eq!(
                two.div_rounded_to::<4>(three, mode),
                two.div_rounded(three, mode)
            );
        }
        // Down-scaling rounds correctly too: 2/3 at 1 digit is 0.7.
        assert_eq!(two.div_rounded_to::<1>(three, HalfUp).0, 7);
        // Checked forms: zero divisor and overflow become None, everything
        // else matches the panicking form.
        assert_eq!(
            two.checked_div_rounded_to::<8>(Amount64::ZERO, HalfUp),
            None
        );
        assert_eq!(
            Amount64::MAX
                .checked_div_rounded_to::<8>(Amount64::from_str("0.0001").unwrap(), HalfUp),
            None
        );
        assert_eq!(
            two.checked_div_rounded_to::<8>(three, HalfUp),
            Some(two.div_rounded_to::<8>(three, HalfUp))
        );
        assert_eq!(
            two.checked_div_rounded(three, HalfUp),
            Some(two.div_rounded(three, HalfUp))
        );
        assert_eq!(two.checked_div_rounded(Amount64::ZERO, HalfUp), None);
    }

    #[test]
    #[should_panic(expected = "attempt to divide by zero")]
    fn test_div_rounded_to_by_zero() {
        let _ = Amount64::from(1).div_rounded_to::<8>(Amount64::ZERO, Rounding::HalfUp);
    }

    #[test]
    fn test_div_int_rounded() {
        use crate::Rounding::*;
        // Exact .00005 ties: 0.0001 / +-2 across modes and signs.
        assert_eq!(Decimal::<4>(1).div_int_rounded(2, HalfUp).0, 1);
        assert_eq!(Decimal::<4>(1).div_int_rounded(2, HalfDown).0, 0);
        assert_eq!(Decimal::<4>(1).div_int_rounded(2, HalfEven).0, 0);
        assert_eq!(Decimal::<4>(-1).div_int_rounded(2, HalfUp).0, -1);
        assert_eq!(Decimal::<4>(1).div_int_rounded(-2, HalfUp).0, -1);
        // Directional modes: Up is ceil, Down is floor.
        assert_eq!(Decimal::<4>(1).div_int_rounded(3, Up).0, 1);
        assert_eq!(Decimal::<4>(-1).div_int_rounded(3, Up).0, 0);
        assert_eq!(Decimal::<4>(-1).div_int_rounded(3, Down).0, -1);
        // Exact division never adjusts, whatever the mode.
        assert_eq!(Amount64::MAX.div_int_rounded(1, Up), Amount64::MAX);
        assert_eq!(Amount64::MAX.div_int_rounded(-1, Up), Amount64::MIN);
        // Checked form: None only on a zero divisor.
        assert_eq!(Amount64::from(1).checked_div_int_rounded(0, HalfUp), None);
        assert_eq!(
            Amount64::from(1).checked_div_int_rounded(3, HalfUp),
            Some(Amount64::from(1).div_int_rounded(3, HalfUp))
        );

        // Self-check: agrees with div_rounded by the same whole number.
        let mut state = 0x9E3779B97F4A7C15u64;
        let mut next = move || {
            state ^= state >> 12;
            state ^= state << 25;
            state ^= state >> 27;
            state.wrapping_mul(0x2545F4914F6CDD1D)
        };
        for _ in 0..2000 {
            let a = (next() as i64) >> 20;
            let n = (next() as i64) >> 49;
            if n == 0 {
                continue;
            }
            let da = Decimal::<4>(a);
            let dn = Decimal::<4>::from(n);
            for mode in [HalfUp, HalfDown, HalfEven, Down, Up] {
                assert_eq!(
                    da.div_int_rounded(n, mode),
                    da.div_rounded(dn, mode),
                    "div_int_rounded {a} / {n}"
                );
            }
        }
    }

    #[test]
    #[should_panic(expected = "attempt to divide by zero")]
    fn test_div_int_rounded_by_zero() {
        let _ = Amount64::from(1).div_int_rounded(0, Rounding::HalfUp);
    }

    #[test]
    fn test_sqrt() {
        use crate::Rounding::*;
        // Exact roots stay exact in every mode.
        for mode in [HalfUp, HalfDown, HalfEven, Down, Up] {
            assert_eq!(
                Amount64::from_str("2.25").unwrap().sqrt_rounded(mode),
                Amount64::from_str("1.5").unwrap()
            );
            assert_eq!(Amount64::from(144).sqrt_rounded(mode), Amount64::from(12));
            assert_eq!(Amount64::ZERO.sqrt_rounded(mode), Amount64::ZERO);
        }
        // sqrt(2) = 1.41421356...: Down truncates, Up ceils, halves round.
        let two = Amount64::from(2);
        assert_eq!(two.sqrt().0, 14142);
        assert_eq!(two.sqrt_rounded(Down).0, 14142);
        assert_eq!(two.sqrt_rounded(Up).0, 14143);
        // sqrt(3) = 1.7320508...: the dropped part is above the half.
        assert_eq!(Amount64::from(3).sqrt().0, 17321);
        assert_eq!(Amount64::from(3).sqrt_rounded(Down).0, 17320);
        // Negative input; checked_sqrt mirrors core's checked_isqrt.
        assert_eq!(Amount64::from(-1).checked_sqrt_rounded(HalfUp), None);
        assert_eq!(Amount64::from(-1).checked_sqrt(), None);
        assert_eq!(
            Amount64::from(2).checked_sqrt(),
            Some(Amount64::from(2).sqrt())
        );
        // DIGITS = 19 holds only values below one, whose square root grows:
        // near the top of the range it overflows, further down it works.
        assert_eq!(Decimal::<19>(i64::MAX).checked_sqrt_rounded(HalfUp), None);
        let quarter = Decimal::<19>(2_500_000_000_000_000_000); // 0.25
        assert_eq!(
            quarter.checked_sqrt_rounded(HalfUp),
            Some(Decimal::<19>(5_000_000_000_000_000_000))
        );

        // Self-check against an independently rounded reference across
        // random values and every mode.
        let mut state = 0xC0FFEE123456789Fu64;
        let mut next = move || {
            state ^= state >> 12;
            state ^= state << 25;
            state ^= state >> 27;
            state.wrapping_mul(0x2545F4914F6CDD1D)
        };
        for i in 0..5000 {
            // Sweep magnitudes from cents to the full i64 range.
            let a = (next() >> (i % 64)) as i64 & i64::MAX;
            let da = Decimal::<4>(a);
            let n = a as u128 * 10_000;
            let s = n.isqrt();
            let rem = n - s * s;
            for mode in [HalfUp, HalfDown, HalfEven, Down, Up] {
                let want = s as i64
                    + match mode {
                        Down => 0,
                        Up => (rem != 0) as i64,
                        _ => (rem > s) as i64,
                    };
                assert_eq!(da.sqrt_rounded(mode).0, want, "sqrt {a} mode {mode:?}");
            }
            // The floor root squared never exceeds the value; one ulp more
            // always does.
            let f = da.sqrt_rounded(Down).0 as u128;
            assert!(f * f <= n && (f + 1) * (f + 1) > n);
        }
    }

    #[test]
    #[should_panic(expected = "argument of integer square root cannot be negative")]
    fn test_sqrt_negative_panics() {
        let _ = Amount64::from(-4).sqrt();
    }

    #[test]
    fn test_mul_div_rounded() {
        use crate::Rounding::*;
        let total = Amount64::from(100);
        // Pro-rata thirds; the exact product is rounded once.
        assert_eq!(
            total
                .mul_div_rounded(Amount64::from(1), Amount64::from(3), HalfUp)
                .0,
            333_333
        );
        assert_eq!(
            total
                .mul_div_rounded(Amount64::from(2), Amount64::from(3), HalfUp)
                .0,
            666_667
        );
        // b and c may be 8-digit rates; their scale cancels.
        let part = Rate64::from_str("0.12345678").unwrap();
        let whole = Rate64::from_str("0.98765432").unwrap();
        let got = total.mul_div_rounded(part, whole, HalfUp);
        assert_eq!(got.0, 125_000); // 100 * 0.12499999886... = 12.5000
        // c == ONE (mantissa 10^S) degenerates to the cross-scale multiply.
        for mode in [HalfUp, HalfDown, HalfEven, Down, Up] {
            assert_eq!(
                total.mul_div_rounded(part, Rate64::ONE, mode),
                total.mul_rounded(part, mode)
            );
        }
        // Single rounding beats the two-step ratio round-trip: 1/3 as an
        // 8-digit rate then times 3e10 accumulates the rate's error.
        let big = Amount64::from(30_000_000_000i64);
        let exact = big.mul_div_rounded(Amount64::from(1), Amount64::from(3), HalfUp);
        assert_eq!(exact, Amount64::from(10_000_000_000i64));
        let two_step = big.mul_rounded(
            Amount64::from(1).div_rounded_to::<8>(Amount64::from(3), HalfUp),
            HalfUp,
        );
        assert_ne!(exact, two_step);
        // Overflow and zero-divisor surface through the checked variant.
        assert_eq!(
            Amount64::MAX.checked_mul_div_rounded(Amount64::from(2), Amount64::from(1), HalfUp),
            None
        );
        assert_eq!(
            total.checked_mul_div_rounded(Amount64::from(1), Amount64::ZERO, HalfUp),
            None
        );

        // Random differential against a 256-bit-free i128 reference (inputs
        // sized so the product fits i128 comfortably).
        let mut state = 0xFEEDFACE8BADF00Du64;
        let mut next = move || {
            state ^= state >> 12;
            state ^= state << 25;
            state ^= state >> 27;
            state.wrapping_mul(0x2545F4914F6CDD1D)
        };
        for _ in 0..5000 {
            let a = (next() as i64) >> 20;
            let b = (next() as i64) >> 20;
            let c = (next() as i64) >> 40;
            if c == 0 {
                continue;
            }
            let num = a as i128 * b as i128;
            let q = num / c as i128;
            let r = num % c as i128;
            for mode in [HalfUp, HalfDown, HalfEven, Down, Up] {
                let want = {
                    let neg = (num < 0) != ((c as i128) < 0);
                    let qa = q.unsigned_abs();
                    let ra = r.unsigned_abs();
                    let da = (c as i128).unsigned_abs();
                    let up = match mode {
                        Down => neg && ra != 0,
                        Up => !neg && ra != 0,
                        HalfUp => 2 * ra >= da,
                        HalfDown => 2 * ra > da,
                        HalfEven => 2 * ra > da || (2 * ra == da && qa & 1 == 1),
                    };
                    let m = qa + up as u128;
                    // The symmetric range caps magnitudes at i64::MAX.
                    if m >> 63 != 0 {
                        None
                    } else if neg {
                        Some(-(m as i64))
                    } else {
                        Some(m as i64)
                    }
                };
                assert_eq!(
                    Decimal::<4>(a)
                        .checked_mul_div_rounded(Decimal::<4>(b), Decimal::<4>(c), mode)
                        .map(|v| v.0),
                    want,
                    "mul_div {a} * {b} / {c} mode {mode:?}"
                );
            }
        }
    }

    #[test]
    fn test_error_kind_accessors() {
        // kind() returns the variant itself.
        assert_eq!(AmountErrorKind::Empty.kind(), &AmountErrorKind::Empty);
        assert_eq!(AmountErrorKind::Inexact.kind(), &AmountErrorKind::Inexact);
        // Display goes through __description for every variant.
        assert_eq!(
            format!("{}", AmountErrorKind::Empty),
            "cannot parse integer from empty string"
        );
        assert_eq!(
            format!("{}", AmountErrorKind::InvalidDigit),
            "invalid symbol found in string"
        );
        assert_eq!(
            format!("{}", AmountErrorKind::Overflow),
            "number too large to fit in target type"
        );
        assert_eq!(
            format!("{}", AmountErrorKind::Inexact),
            "value cannot be represented exactly at the target scale"
        );
    }

    #[test]
    fn test_parse_decimal_i64_default() {
        use crate::parse_decimal_i64;
        // The non-rounded wrapper delegates with HalfUp.
        assert_eq!(parse_decimal_i64("1.23455", 4), Ok(12346));
        assert_eq!(parse_decimal_i64("-1.23455", 4), Ok(-12346));
        assert_eq!(parse_decimal_i64("1.5", 8), Ok(150_000_000));
        assert_eq!(
            parse_decimal_i64("bad", 4),
            Err(AmountErrorKind::InvalidDigit)
        );
    }

    #[test]
    fn test_new_and_conversions() {
        // new() is zero.
        assert_eq!(Amount64::new(), Amount64::ZERO);
        assert_eq!(Amount64::new().0, 0);

        // from_i64: in-range scales up exactly, out-of-range overflows.
        assert_eq!(Amount64::from_i64(3), Ok(Decimal::<4>(30000)));
        assert_eq!(Amount64::from_i64(-3), Ok(Decimal::<4>(-30000)));
        assert_eq!(
            Amount64::from_i64(Amount64::INT_MAX),
            Ok(Decimal::<4>(Amount64::INT_MAX * Amount64::SCALE_INT))
        );
        assert_eq!(
            Amount64::from_i64(Amount64::INT_MAX + 1),
            Err(AmountErrorKind::Overflow)
        );
        assert_eq!(
            Amount64::from_i64(Amount64::INT_MIN - 1),
            Err(AmountErrorKind::Overflow)
        );

        // to_i64 truncates toward zero.
        assert_eq!(Decimal::<4>(19999).to_i64(), 1);
        assert_eq!(Decimal::<4>(-19999).to_i64(), -1);
        assert_eq!(Decimal::<4>(0).to_i64(), 0);

        // to_f64 divides by the scale (exact for these values).
        assert_eq!(Decimal::<4>(15000).to_f64(), 1.5);
        assert_eq!(Decimal::<4>(-15000).to_f64(), -1.5);

        // from_f64 rejects out-of-range values; from_f32 delegates.
        assert_eq!(Amount64::from_f64(1e30), Err(AmountErrorKind::Overflow));
        assert_eq!(Amount64::from_f64(-1e30), Err(AmountErrorKind::Overflow));
        assert_eq!(Amount64::from_f32(1.5), Ok(Decimal::<4>(15000)));
        assert_eq!(Amount64::from_f32(1e30), Err(AmountErrorKind::Overflow));
    }

    #[test]
    fn test_from_decimal_parts_rounded_scale_up() {
        use crate::Rounding::*;
        // Zero mantissa short-circuits at any exponent.
        assert_eq!(
            Amount64::from_decimal_parts_rounded(0, 1000, HalfUp),
            Ok(Decimal::<4>(0))
        );
        assert_eq!(
            Amount64::from_decimal_parts_rounded(0, -1000, Down),
            Ok(Decimal::<4>(0))
        );
        // Scale up is exact regardless of mode.
        assert_eq!(
            Amount64::from_decimal_parts_rounded(5, 2, Down),
            Ok(Decimal::<4>(5_000_000))
        );
        assert_eq!(
            Amount64::from_decimal_parts_rounded(123, -2, HalfUp),
            Ok(Decimal::<4>(12300))
        );
        // The power of ten itself overflows i128.
        assert_eq!(
            Amount64::from_decimal_parts_rounded(1, 1000, HalfUp),
            Err(AmountErrorKind::Overflow)
        );
        // Scaled value fits i128 but not the i64 backing.
        assert_eq!(
            Amount64::from_decimal_parts_rounded(i64::MAX as i128 + 1, -4, HalfUp),
            Err(AmountErrorKind::Overflow)
        );
    }

    #[test]
    fn test_from_str_const_runtime() {
        // The runtime path matches FromStr with HalfUp.
        assert_eq!(Amount64::from_str_const("19.99").0, 199_900);
        assert_eq!(Amount64::from_str_const("-1.00005").0, -10001);
    }

    #[test]
    #[should_panic(expected = "invalid decimal literal")]
    fn test_from_str_const_invalid_panics() {
        let _ = Amount64::from_str_const("not a number");
    }

    #[test]
    fn test_from_str_ref() {
        // From<&str> parses like FromStr (HalfUp).
        assert_eq!(Amount64::from("1.5"), Decimal::<4>(15000));
        assert_eq!(Amount64::from("-0.0001"), Decimal::<4>(-1));
        assert_eq!(Amount64::from("1.00005"), Decimal::<4>(10001));
    }

    #[test]
    #[should_panic(expected = "InvalidDigit")]
    fn test_from_str_ref_invalid_panics() {
        let _ = Amount64::from("bogus");
    }

    #[test]
    fn test_abs_signum_predicates() {
        assert_eq!(Decimal::<4>(-12345).abs(), Decimal::<4>(12345));
        assert_eq!(Decimal::<4>(12345).abs(), Decimal::<4>(12345));
        assert_eq!(Amount64::ZERO.abs(), Amount64::ZERO);

        assert!(Amount64::from(10).is_positive());
        assert!(!Amount64::ZERO.is_positive());
        assert!(!Amount64::from(-10).is_positive());
        assert!(Amount64::from(-10).is_negative());
        assert!(!Amount64::ZERO.is_negative());
        assert!(!Amount64::from(10).is_negative());

        assert_eq!(Amount64::from(10).signum(), Amount64::ONE);
        assert_eq!(Amount64::from(-10).signum(), Amount64::MINUS_ONE);
        assert_eq!(Amount64::ZERO.signum(), Amount64::ZERO);
    }

    #[test]
    fn test_checked_add_sub_edges() {
        // Success arm of checked_add.
        assert_eq!(
            Amount64::from(1).checked_add(Amount64::from(2)),
            Some(Amount64::from(3))
        );
        // Overflow arms on both sides of zero.
        assert_eq!(Amount64::MIN.checked_sub(Amount64::from(1)), None);
        assert_eq!(Amount64::from(-1).checked_add(Amount64::MIN), None);
    }

    #[test]
    fn test_ceil() {
        assert_eq!(Decimal::<4>(10000).ceil(), Decimal::<4>(10000));
        assert_eq!(Decimal::<4>(10001).ceil(), Decimal::<4>(20000));
        assert_eq!(Decimal::<4>(19999).ceil(), Decimal::<4>(20000));
        assert_eq!(Decimal::<4>(0).ceil(), Decimal::<4>(0));

        // Exact negatives pass through unchanged.
        assert_eq!(Decimal::<4>(-10000).ceil(), Decimal::<4>(-10000));
        // Negative non-integers truncate toward +inf (mathematical ceiling).
        assert_eq!(Decimal::<4>(-10001).ceil(), Decimal::<4>(-10000));
        assert_eq!(Decimal::<4>(-19999).ceil(), Decimal::<4>(-10000));
        assert_eq!(Decimal::<4>(-9999).ceil(), Decimal::<4>(0));
        // ceil(x) == -floor(-x)
        for m in [-19999i64, -10001, -9999, 0, 9999, 10001, 19999] {
            assert_eq!(Decimal::<4>(m).ceil(), -Decimal::<4>(-m).floor(), "{m}");
        }
    }

    #[test]
    fn test_round_dp() {
        use crate::Rounding::*;
        let v = Amount64::from_str_const("12.3456");
        assert_eq!(v.round_dp(2, HalfUp), Amount64::from_str_const("12.35"));
        assert_eq!(v.round_dp(2, Down), Amount64::from_str_const("12.34"));
        assert_eq!(v.round_dp(3, HalfUp), Amount64::from_str_const("12.346"));
        // dp >= DIGITS is the identity.
        assert_eq!(v.round_dp(4, HalfUp), v);
        assert_eq!(v.round_dp(200, HalfUp), v);
        // dp == 0 matches round_to, every mode.
        let w = Amount64::from_str_const("-7.5000");
        for mode in [HalfUp, HalfDown, HalfEven, Down, Up] {
            assert_eq!(v.round_dp(0, mode), v.round_to(mode), "{mode:?}");
            assert_eq!(w.round_dp(0, mode), w.round_to(mode), "{mode:?}");
        }
        // HalfEven ties look at the parity of the kept digit.
        assert_eq!(
            Amount64::from_str_const("0.0250").round_dp(2, HalfEven),
            Amount64::from_str_const("0.02")
        );
        assert_eq!(
            Amount64::from_str_const("0.0350").round_dp(2, HalfEven),
            Amount64::from_str_const("0.04")
        );
        // Negative values round on the magnitude with directional modes.
        let neg = Amount64::from_str_const("-12.3456");
        assert_eq!(neg.round_dp(2, Down), Amount64::from_str_const("-12.35"));
        assert_eq!(neg.round_dp(2, Up), Amount64::from_str_const("-12.34"));
        // The very edge of the range overflows.
        assert_eq!(Amount64::MAX.checked_round_dp(2, Up), None);
        assert_eq!(Amount64::MIN.checked_round_dp(2, Down), None);
        // round100 delegates to round_dp(2, HalfUp).
        assert_eq!(v.round100(), v.round_dp(2, HalfUp));
    }

    #[test]
    #[should_panic(expected = "attempt to round with overflow")]
    fn test_round_dp_edge_overflow_panics() {
        let _ = Amount64::MAX.round_dp(2, Rounding::Up);
    }

    #[test]
    fn test_split_evenly() {
        // Doc case plus invariants over random totals and part counts.
        let s = Amount64::from_str_const("100.00").split_evenly(3);
        assert_eq!(s.high.0, 333_334);
        assert_eq!(s.high_count, 1);
        assert_eq!(s.low.0, 333_333);
        assert_eq!(s.low_count, 2);

        // Exact split: high == low, high_count == 0.
        let s = Amount64::from_str_const("100.00").split_evenly(4);
        assert_eq!((s.high, s.high_count), (s.low, 0));
        assert_eq!((s.low.0, s.low_count), (250_000, 4));

        // n == 1 and zero totals.
        let v = Amount64::from_str_const("-3.1415");
        let s = v.split_evenly(1);
        assert_eq!((s.low, s.low_count, s.high_count), (v, 1, 0));
        let s = Amount64::ZERO.split_evenly(7);
        assert_eq!((s.low, s.low_count, s.high_count), (Amount64::ZERO, 7, 0));

        assert_eq!(v.checked_split_evenly(0), None);

        // Conservation and shape over random inputs, both signs.
        let mut state = 0x5EED5EED5EEDu64;
        let mut rng = move || {
            state ^= state >> 12;
            state ^= state << 25;
            state ^= state >> 27;
            state.wrapping_mul(0x2545F4914F6CDD1D)
        };
        for _ in 0..20000 {
            let m = (rng() as i64) >> (rng() % 40);
            let n = 1 + (rng() % 999) as u32;
            let v = Decimal::<4>(m);
            let s = v.split_evenly(n);
            assert_eq!(s.high_count + s.low_count, n);
            assert_eq!(
                s.high.0 as i128 * s.high_count as i128 + s.low.0 as i128 * s.low_count as i128,
                m as i128,
                "conservation {m} / {n}"
            );
            if s.high_count > 0 {
                assert_eq!(s.high.0 - s.low.0, if m < 0 { -1 } else { 1 }, "{m} {n}");
            } else {
                assert_eq!(s.high, s.low);
            }
        }
    }

    #[test]
    #[should_panic(expected = "attempt to divide by zero")]
    fn test_split_evenly_zero_panics() {
        let _ = Amount64::from(1).split_evenly(0);
    }

    #[test]
    fn test_checked_rem_powi_recip_round_to() {
        use crate::Rounding::*;
        let a = Amount64::from_str_const("7.5");
        let b = Amount64::from(2);
        assert_eq!(a.checked_rem(b), Some(Amount64::from_str_const("1.5")));
        assert_eq!(a.checked_rem(Amount64::ZERO), None);

        assert_eq!(b.checked_powi(0), Some(Amount64::ONE));
        assert_eq!(b.checked_powi(1), Some(b));
        assert_eq!(b.checked_powi(10), Some(Amount64::from(1024)));
        assert_eq!(Amount64::MAX.checked_powi(2), None);
        // x^2 fits but x^3 does not: exp = 3 overflows at the final odd-bit
        // multiply, exp = 7 at the in-loop odd-bit multiply.
        let big = Amount64::from(100_000);
        assert_eq!(big.checked_powi(3), None);
        assert_eq!(big.checked_powi(7), None);

        assert_eq!(b.checked_recip(), Some(Amount64::from_str_const("0.5")));
        assert_eq!(Amount64::ZERO.checked_recip(), None);
        // At DIGITS = 10 the reciprocal of the smallest positive value needs
        // mantissa 10^20 > i64::MAX: the overflow arm of checked_recip.
        assert_eq!(Decimal::<10>::from_bits(1).checked_recip(), None);

        assert_eq!(a.checked_round_to(Down), Some(Amount64::from(7)));
        assert_eq!(Amount64::MAX.checked_round_to(Up), None);
        assert_eq!(Amount64::MIN.checked_round_to(Down), None);
    }

    #[test]
    #[should_panic(expected = "attempt to calculate the remainder")]
    fn test_rem_by_zero_panics() {
        let _ = Amount64::from(1) % Amount64::ZERO;
    }

    #[test]
    #[should_panic(expected = "attempt to multiply with overflow")]
    fn test_powi_overflow_panics() {
        let _ = Amount64::MAX.powi(2);
    }

    #[test]
    #[should_panic(expected = "attempt to divide by zero")]
    fn test_recip_zero_panics() {
        let _ = Amount64::ZERO.recip();
    }

    #[test]
    #[should_panic(expected = "attempt to divide with overflow")]
    fn test_recip_overflow_panics() {
        let _ = Decimal::<10>::from_bits(1).recip();
    }

    #[test]
    #[should_panic(expected = "attempt to round with overflow")]
    fn test_round100_edge_overflow_panics() {
        // At scale 3 the fraction of MAX is 7/10 >= 1/2, so rounding to
        // 1/100 steps past the range.
        let _ = Decimal::<3>::MAX.round100();
    }

    #[test]
    #[should_panic(expected = "attempt to round with overflow")]
    fn test_ceil_edge_overflow_panics() {
        // MAX has a non-zero fraction, so ceiling steps past the range; this
        // must panic in every build profile, never wrap.
        let _ = Amount64::MAX.ceil();
    }

    #[test]
    #[should_panic(expected = "attempt to round with overflow")]
    fn test_floor_edge_overflow_panics() {
        let _ = Amount64::MIN.floor();
    }

    #[test]
    fn test_f64_eq_uses_type_scale() {
        // Regression: `f64 == Decimal<DIGITS>` once hardcoded Amount64's
        // scale, so it was wrong for any other DIGITS.
        assert!(0.5f64 == Rate64::from_str_const("0.5"));
        assert!(0.5f64 != Rate64::from_str_const("0.00005"));
        assert!(2.0f64 == Decimal::<0>::from(2));
        assert!(0.5f64 == Amount64::from_str_const("0.5"));
    }

    #[test]
    fn test_round_to_halfeven_negative_ties() {
        use crate::Rounding::HalfEven;
        // -1.5: integer part -1 is odd -> rounds away to -2.
        assert_eq!(
            Decimal::<4>(-15000).round_to(HalfEven),
            Decimal::<4>(-20000)
        );
        // -2.5: integer part -2 is even -> stays -2.
        assert_eq!(
            Decimal::<4>(-25000).round_to(HalfEven),
            Decimal::<4>(-20000)
        );
        // Below/above the negative half round directionally.
        assert_eq!(
            Decimal::<4>(-16000).round_to(HalfEven),
            Decimal::<4>(-20000)
        );
        assert_eq!(
            Decimal::<4>(-14000).round_to(HalfEven),
            Decimal::<4>(-10000)
        );
    }

    #[test]
    fn test_fract() {
        assert_eq!(Decimal::<4>(36000).fract(), Decimal::<4>(6000));
        assert_eq!(Decimal::<4>(-36000).fract(), Decimal::<4>(-6000));
        assert_eq!(Decimal::<4>(30000).fract(), Decimal::<4>(0));
    }

    #[test]
    #[should_panic(expected = "attempt to multiply with overflow")]
    fn test_mul_overflow_panics() {
        let _ = Amount64::MAX * Amount64::from(2);
    }

    #[test]
    #[should_panic(expected = "attempt to divide with overflow")]
    fn test_div_overflow_panics() {
        let _ = Amount64::MAX / Amount64::from_str_const("0.0001");
    }

    #[test]
    #[should_panic(expected = "attempt to compute square root with overflow")]
    fn test_sqrt_overflow_panics() {
        // At DIGITS = 19 every value is below one, so the root grows and
        // overflows near the top of the range.
        let _ = Decimal::<19>(i64::MAX).sqrt();
    }

    #[test]
    #[should_panic(expected = "attempt to divide by zero")]
    fn test_mul_div_rounded_by_zero_panics() {
        let _ =
            Amount64::from(1).mul_div_rounded(Amount64::from(1), Amount64::ZERO, Rounding::HalfUp);
    }

    #[test]
    #[should_panic(expected = "attempt to divide with overflow")]
    fn test_mul_div_rounded_overflow_panics() {
        let _ =
            Amount64::MAX.mul_div_rounded(Amount64::from(2), Amount64::from(1), Rounding::HalfUp);
    }

    #[test]
    fn test_bits_and_bytes() {
        let n = Amount64::from_bits(0x1234567890123456u64);
        assert_eq!(n.0, 0x1234567890123456i64);
        assert_eq!(n.to_bits(), 0x1234567890123456u64);
        // Negative values round-trip through the u64 bit pattern.
        assert_eq!(
            Amount64::from_bits(Decimal::<4>(-1).to_bits()),
            Decimal::<4>(-1)
        );

        assert_eq!(n.swap_bytes().to_bits(), 0x5634129078563412u64);
        assert_eq!(n.swap_bytes().swap_bytes(), n);

        let be = [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56];
        let le = [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12];
        assert_eq!(n.to_be_bytes(), be);
        assert_eq!(n.to_le_bytes(), le);
        assert_eq!(Amount64::from_be_bytes(be), n);
        assert_eq!(Amount64::from_le_bytes(le), n);
        // Native order matches the platform's endianness and round-trips.
        let ne = n.to_ne_bytes();
        assert_eq!(ne, if cfg!(target_endian = "big") { be } else { le });
        assert_eq!(Amount64::from_ne_bytes(ne), n);
    }

    #[test]
    fn test_clamp_min_max() {
        let lo = Amount64::MINUS_ONE;
        let hi = Amount64::ONE;
        assert_eq!(Amount64::from(2).clamp(lo, hi), hi);
        assert_eq!(Amount64::from(-2).clamp(lo, hi), lo);
        assert_eq!(Amount64::ZERO.clamp(lo, hi), Amount64::ZERO);

        assert_eq!(hi.min(lo), lo);
        assert_eq!(lo.min(hi), lo);
        assert_eq!(hi.max(lo), hi);
        assert_eq!(lo.max(hi), hi);
        let a = Amount64::from(3);
        assert_eq!(a.min(a), a);
        assert_eq!(a.max(a), a);
    }

    #[test]
    fn test_mixed_comparisons() {
        let a = Amount64::from(2);
        // Decimal vs i64, both directions.
        assert!(a > 1i64);
        assert!(a < 3i64);
        assert!(a == 2i64);
        assert!(1i64 < a);
        assert!(3i64 > a);
        assert!(2i64 == a);
        assert!(2i64 != Amount64::from_str_const("2.5"));
        // Decimal vs f64, both directions; fractions participate exactly.
        assert!(a > 1.5f64);
        assert!(a < 2.5f64);
        assert!(a == 2.0f64);
        assert!(2.0f64 == a);
        assert!(2.5f64 != a);
        assert!(Amount64::from_str_const("2.5") == 2.5f64);
    }

    #[test]
    fn test_from_saturating_and_f32() {
        // From<f64> saturates out-of-range values instead of erroring.
        assert_eq!(Amount64::from(1e30f64), Amount64::MAX);
        assert_eq!(Amount64::from(-1e30f64), Amount64::MIN);
        // In-range f32/f64 conversions scale exactly.
        assert_eq!(Amount64::from(1.5f32), Decimal::<4>(15000));
        assert_eq!(Amount64::from(-2.25f32), Decimal::<4>(-22500));
        // From<i32>.
        assert_eq!(Amount64::from(3i32), Decimal::<4>(30000));
        assert_eq!(Amount64::from(-3i32), Decimal::<4>(-30000));
    }

    #[test]
    fn test_mixed_arithmetic_ops() {
        let a = Amount64::from(2);
        // Decimal (+|-) primitive scales the primitive up.
        assert_eq!(a + 3i64, Amount64::from(5));
        assert_eq!(a + 3i32, Amount64::from(5));
        assert_eq!(a + 0.5f64, Amount64::from_str_const("2.5"));
        assert_eq!(a - 3i64, Amount64::from(-1));
        assert_eq!(a - 1i32, Amount64::from(1));
        assert_eq!(a - 0.5f64, Amount64::from_str_const("1.5"));

        // i64 (+|-) Decimal rounds the decimal half-away-from-zero first.
        assert_eq!(10i64 + Amount64::from_str_const("2.5"), 13);
        assert_eq!(10i64 + Amount64::from_str_const("2.4999"), 12);
        assert_eq!(10i64 + Amount64::from_str_const("-2.5"), 7);
        assert_eq!(10i64 - Amount64::from_str_const("2.5"), 7);
        assert_eq!(10i64 - Amount64::from_str_const("2.4999"), 8);
        assert_eq!(10i64 - Amount64::from_str_const("-2.5"), 13);

        // f64 (+|-) Decimal go through to_f64 (exact for these values).
        assert_eq!(1.5f64 + Amount64::from_str_const("2.25"), 3.75f64);
        assert_eq!(10.0f64 - Amount64::from_str_const("2.5"), 7.5f64);

        // Multiplying by integers scales the raw value directly.
        assert_eq!(a * 3i64, Amount64::from(6));
        assert_eq!(a * 3i32, Amount64::from(6));
        // i64 * Decimal treats the i64 as a raw mantissa and returns one.
        assert_eq!(20000i64 * Amount64::from(3), 60000i64);
    }

    #[test]
    fn test_assign_ops() {
        let mut a = Amount64::from(10);
        a += Amount64::from(2);
        assert_eq!(a, Amount64::from(12));
        a -= Amount64::from(4);
        assert_eq!(a, Amount64::from(8));
        a *= Amount64::from(2);
        assert_eq!(a, Amount64::from(16));
        a /= Amount64::from(4);
        assert_eq!(a, Amount64::from(4));
        a %= Amount64::from_str_const("2.5");
        assert_eq!(a, Amount64::from_str_const("1.5"));
    }

    #[test]
    fn test_sum_product_iters() {
        let vals = [Amount64::from(1), Amount64::from(2), Amount64::from(3)];
        // By-value and by-reference Sum.
        assert_eq!(vals.iter().copied().sum::<Amount64>(), Amount64::from(6));
        assert_eq!(vals.iter().sum::<Amount64>(), Amount64::from(6));
        // By-value and by-reference Product.
        assert_eq!(
            vals.iter().copied().product::<Amount64>(),
            Amount64::from(6)
        );
        assert_eq!(vals.iter().product::<Amount64>(), Amount64::from(6));
        // Empty iterators yield the identities.
        assert_eq!(
            core::iter::empty::<Amount64>().sum::<Amount64>(),
            Amount64::ZERO
        );
        assert_eq!(
            core::iter::empty::<Amount64>().product::<Amount64>(),
            Amount64::ONE
        );
    }

    #[test]
    fn test_display_error_fallback() {
        // A precision beyond the 128-byte format buffer cannot be rendered;
        // Display falls back to the documented error marker.
        assert_eq!(format!("{:.200}", Decimal::<4>(10000)), "Amount::ERROR");
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serde() {
        use core::fmt::Write as _;
        use serde::de::value::{Error as ValueError, StrDeserializer};
        use serde::ser::{Error as _, Impossible};
        use serde::{Deserialize, Serialize, Serializer};
        use std::string::String;

        // Minimal hand-rolled serializer: only `collect_str` (the one entry
        // point `Decimal`'s `Serialize` uses) does real work; every other
        // shape is rejected.
        struct StrCollector;

        macro_rules! reject {
            ($($m:ident($($arg:ty),*) -> $ok:ty;)*) => {$(
                fn $m(self, $(_: $arg),*) -> Result<$ok, ValueError> {
                    Err(ValueError::custom("unsupported"))
                }
            )*};
        }

        impl Serializer for StrCollector {
            type Ok = String;
            type Error = ValueError;
            type SerializeSeq = Impossible<String, ValueError>;
            type SerializeTuple = Impossible<String, ValueError>;
            type SerializeTupleStruct = Impossible<String, ValueError>;
            type SerializeTupleVariant = Impossible<String, ValueError>;
            type SerializeMap = Impossible<String, ValueError>;
            type SerializeStruct = Impossible<String, ValueError>;
            type SerializeStructVariant = Impossible<String, ValueError>;

            fn collect_str<T>(self, value: &T) -> Result<String, ValueError>
            where
                T: ?Sized + core::fmt::Display,
            {
                let mut out = String::new();
                write!(out, "{value}").map_err(|_| ValueError::custom("fmt"))?;
                Ok(out)
            }

            reject! {
                serialize_bool(bool) -> String;
                serialize_i8(i8) -> String;
                serialize_i16(i16) -> String;
                serialize_i32(i32) -> String;
                serialize_i64(i64) -> String;
                serialize_u8(u8) -> String;
                serialize_u16(u16) -> String;
                serialize_u32(u32) -> String;
                serialize_u64(u64) -> String;
                serialize_f32(f32) -> String;
                serialize_f64(f64) -> String;
                serialize_char(char) -> String;
                serialize_str(&str) -> String;
                serialize_bytes(&[u8]) -> String;
                serialize_none() -> String;
                serialize_unit() -> String;
                serialize_unit_struct(&'static str) -> String;
                serialize_unit_variant(&'static str, u32, &'static str) -> String;
                serialize_seq(Option<usize>) -> Self::SerializeSeq;
                serialize_tuple(usize) -> Self::SerializeTuple;
                serialize_tuple_struct(&'static str, usize) -> Self::SerializeTupleStruct;
                serialize_tuple_variant(&'static str, u32, &'static str, usize) -> Self::SerializeTupleVariant;
                serialize_map(Option<usize>) -> Self::SerializeMap;
                serialize_struct(&'static str, usize) -> Self::SerializeStruct;
                serialize_struct_variant(&'static str, u32, &'static str, usize) -> Self::SerializeStructVariant;
            }

            fn serialize_some<T>(self, _: &T) -> Result<String, ValueError>
            where
                T: ?Sized + Serialize,
            {
                Err(ValueError::custom("unsupported"))
            }

            fn serialize_newtype_struct<T>(
                self,
                _: &'static str,
                _: &T,
            ) -> Result<String, ValueError>
            where
                T: ?Sized + Serialize,
            {
                Err(ValueError::custom("unsupported"))
            }

            fn serialize_newtype_variant<T>(
                self,
                _: &'static str,
                _: u32,
                _: &'static str,
                _: &T,
            ) -> Result<String, ValueError>
            where
                T: ?Sized + Serialize,
            {
                Err(ValueError::custom("unsupported"))
            }
        }

        fn de(s: &str) -> Result<Amount64, ValueError> {
            Amount64::deserialize(StrDeserializer::<ValueError>::new(s))
        }

        // Serialize emits the Display string (trailing zeros trimmed).
        let a = Amount64::from_str_const("1.0001");
        assert_eq!(a.serialize(StrCollector), Ok(String::from("1.0001")));
        assert_eq!(
            Amount64::from_str_const("-0.5").serialize(StrCollector),
            Ok(String::from("-0.5"))
        );
        assert_eq!(
            Amount64::ZERO.serialize(StrCollector),
            Ok(String::from("0"))
        );

        // Deserialize parses the string form back with HalfUp, like FromStr.
        assert_eq!(de("1.0001"), Ok(a));
        assert_eq!(de("1.00005"), Ok(Decimal::<4>(10001)));
        assert_eq!(de("-0.5"), Ok(Decimal::<4>(-5000)));

        // Full round-trip through both traits at another scale.
        let r = Rate64::from_str_const("0.12345678");
        let s = r.serialize(StrCollector).unwrap();
        assert_eq!(s, "0.12345678");
        assert_eq!(
            Rate64::deserialize(StrDeserializer::<ValueError>::new(&s)),
            Ok(r)
        );

        // Invalid strings surface as a deserializer error (the message is
        // erased because serde is built without alloc).
        assert!(de("not-a-number").is_err());
        assert!(de("").is_err());
        assert!(de("922337203685477.5808").is_err());

        // A non-string input is a type error, reported through the visitor's
        // expecting() message.
        let non_str =
            Amount64::deserialize(serde::de::value::I32Deserializer::<ValueError>::new(5));
        assert!(non_str.is_err());
    }

    #[cfg(feature = "ufmt")]
    #[test]
    fn test_ufmt() {
        struct StringWriter(std::string::String);
        impl ufmt::uWrite for StringWriter {
            type Error = core::convert::Infallible;
            fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
                self.0.push_str(s);
                Ok(())
            }
        }

        let mut w1 = StringWriter(std::string::String::new());
        let val1 = Decimal::<4>(10000);
        ufmt::uwrite!(&mut w1, "{}", val1).unwrap();
        assert_eq!(w1.0, "1");

        let mut w2 = StringWriter(std::string::String::new());
        let val2 = Decimal::<4>(-10001);
        ufmt::uwrite!(&mut w2, "{}", val2).unwrap();
        assert_eq!(w2.0, "-1.0001");

        let mut w3 = StringWriter(std::string::String::new());
        ufmt::uwrite!(&mut w3, "{:?}", val2).unwrap();
        assert_eq!(w3.0, "Decimal(-10001)");
    }
}