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
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
|
/*
* Copyright (c) 1996, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation is copyrighted
* and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
* materials are provided under terms of a License Agreement between Taligent
* and Sun. This technology is protected by multiple US and International
* patents. This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package java.text;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.spi.NumberFormatProvider;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import sun.util.locale.provider.LocaleProviderAdapter;
import sun.util.locale.provider.ResourceBundleBasedAdapter;
/**
* {@code DecimalFormat} is a concrete subclass of
* {@code NumberFormat} that formats decimal numbers. It has a variety of
* features designed to make it possible to parse and format numbers in any
* locale, including support for Western, Arabic, and Indic digits. It also
* supports different kinds of numbers, including integers (123), fixed-point
* numbers (123.4), scientific notation (1.23E4), percentages (12%), and
* currency amounts ($123). All of these can be localized.
*
* <p>To obtain a {@code NumberFormat} for a specific locale, including the
* default locale, call one of {@code NumberFormat}'s factory methods, such
* as {@code getInstance()}. In general, do not call the
* {@code DecimalFormat} constructors directly, since the
* {@code NumberFormat} factory methods may return subclasses other than
* {@code DecimalFormat}. If you need to customize the format object, do
* something like this:
*
* <blockquote><pre>
* NumberFormat f = NumberFormat.getInstance(loc);
* if (f instanceof DecimalFormat) {
* ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
* }
* </pre></blockquote>
*
* <p>A {@code DecimalFormat} comprises a <em>pattern</em> and a set of
* <em>symbols</em>. The pattern may be set directly using
* {@code applyPattern()}, or indirectly using the API methods. The
* symbols are stored in a {@code DecimalFormatSymbols} object. When using
* the {@code NumberFormat} factory methods, the pattern and symbols are
* read from localized {@code ResourceBundle}s.
*
* <h2>Patterns</h2>
*
* {@code DecimalFormat} patterns have the following syntax:
* <blockquote><pre>
* <i>Pattern:</i>
* <i>PositivePattern</i>
* <i>PositivePattern</i> ; <i>NegativePattern</i>
* <i>PositivePattern:</i>
* <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
* <i>NegativePattern:</i>
* <i>Prefix<sub>opt</sub></i> <i>Number</i> <i>Suffix<sub>opt</sub></i>
* <i>Prefix:</i>
* any Unicode characters except \uFFFE, \uFFFF, and special characters
* <i>Suffix:</i>
* any Unicode characters except \uFFFE, \uFFFF, and special characters
* <i>Number:</i>
* <i>Integer</i> <i>Exponent<sub>opt</sub></i>
* <i>Integer</i> . <i>Fraction</i> <i>Exponent<sub>opt</sub></i>
* <i>Integer:</i>
* <i>MinimumInteger</i>
* #
* # <i>Integer</i>
* # , <i>Integer</i>
* <i>MinimumInteger:</i>
* 0
* 0 <i>MinimumInteger</i>
* 0 , <i>MinimumInteger</i>
* <i>Fraction:</i>
* <i>MinimumFraction<sub>opt</sub></i> <i>OptionalFraction<sub>opt</sub></i>
* <i>MinimumFraction:</i>
* 0 <i>MinimumFraction<sub>opt</sub></i>
* <i>OptionalFraction:</i>
* # <i>OptionalFraction<sub>opt</sub></i>
* <i>Exponent:</i>
* E <i>MinimumExponent</i>
* <i>MinimumExponent:</i>
* 0 <i>MinimumExponent<sub>opt</sub></i>
* </pre></blockquote>
*
* <p>A {@code DecimalFormat} pattern contains a positive and negative
* subpattern, for example, {@code "#,##0.00;(#,##0.00)"}. Each
* subpattern has a prefix, numeric part, and suffix. The negative subpattern
* is optional; if absent, then the positive subpattern prefixed with the
* minus sign ({@code '-' U+002D HYPHEN-MINUS}) is used as the
* negative subpattern. That is, {@code "0.00"} alone is equivalent to
* {@code "0.00;-0.00"}. If there is an explicit negative subpattern, it
* serves only to specify the negative prefix and suffix; the number of digits,
* minimal digits, and other characteristics are all the same as the positive
* pattern. That means that {@code "#,##0.0#;(#)"} produces precisely
* the same behavior as {@code "#,##0.0#;(#,##0.0#)"}.
*
* <p>The prefixes, suffixes, and various symbols used for infinity, digits,
* grouping separators, decimal separators, etc. may be set to arbitrary
* values, and they will appear properly during formatting. However, care must
* be taken that the symbols and strings do not conflict, or parsing will be
* unreliable. For example, either the positive and negative prefixes or the
* suffixes must be distinct for {@code DecimalFormat.parse()} to be able
* to distinguish positive from negative values. (If they are identical, then
* {@code DecimalFormat} will behave as if no negative subpattern was
* specified.) Another example is that the decimal separator and grouping
* separator should be distinct characters, or parsing will be impossible.
*
* <p>The grouping separator is commonly used for thousands, but in some
* countries it separates ten-thousands. The grouping size is a constant number
* of digits between the grouping characters, such as 3 for 100,000,000 or 4 for
* 1,0000,0000. If you supply a pattern with multiple grouping characters, the
* interval between the last one and the end of the integer is the one that is
* used. So {@code "#,##,###,####"} == {@code "######,####"} ==
* {@code "##,####,####"}.
*
* <h3><a id="special_pattern_character">Special Pattern Characters</a></h3>
*
* <p>Many characters in a pattern are taken literally; they are matched during
* parsing and output unchanged during formatting. Special characters, on the
* other hand, stand for other characters, strings, or classes of characters.
* They must be quoted, unless noted otherwise, if they are to appear in the
* prefix or suffix as literals.
*
* <p>The characters listed here are used in non-localized patterns. Localized
* patterns use the corresponding characters taken from this formatter's
* {@code DecimalFormatSymbols} object instead, and these characters lose
* their special status. Two exceptions are the currency sign and quote, which
* are not localized.
*
* <blockquote>
* <table class="striped">
* <caption style="display:none">Chart showing symbol, location, localized, and meaning.</caption>
* <thead>
* <tr>
* <th scope="col" style="text-align:left">Symbol
* <th scope="col" style="text-align:left">Location
* <th scope="col" style="text-align:left">Localized?
* <th scope="col" style="text-align:left">Meaning
* </thead>
* <tbody>
* <tr style="vertical-align:top">
* <th scope="row">{@code 0}
* <td>Number
* <td>Yes
* <td>Digit
* <tr style="vertical-align: top">
* <th scope="row">{@code #}
* <td>Number
* <td>Yes
* <td>Digit, zero shows as absent
* <tr style="vertical-align:top">
* <th scope="row">{@code .}
* <td>Number
* <td>Yes
* <td>Decimal separator or monetary decimal separator
* <tr style="vertical-align: top">
* <th scope="row">{@code -}
* <td>Number
* <td>Yes
* <td>Minus sign
* <tr style="vertical-align:top">
* <th scope="row">{@code ,}
* <td>Number
* <td>Yes
* <td>Grouping separator or monetary grouping separator
* <tr style="vertical-align: top">
* <th scope="row">{@code E}
* <td>Number
* <td>Yes
* <td>Separates mantissa and exponent in scientific notation.
* <em>Need not be quoted in prefix or suffix.</em>
* <tr style="vertical-align:top">
* <th scope="row">{@code ;}
* <td>Subpattern boundary
* <td>Yes
* <td>Separates positive and negative subpatterns
* <tr style="vertical-align: top">
* <th scope="row">{@code %}
* <td>Prefix or suffix
* <td>Yes
* <td>Multiply by 100 and show as percentage
* <tr style="vertical-align:top">
* <th scope="row">{@code \u2030}
* <td>Prefix or suffix
* <td>Yes
* <td>Multiply by 1000 and show as per mille value
* <tr style="vertical-align: top">
* <th scope="row">{@code ¤} ({@code \u00A4})
* <td>Prefix or suffix
* <td>No
* <td>Currency sign, replaced by currency symbol. If
* doubled, replaced by international currency symbol.
* If present in a pattern, the monetary decimal/grouping separators
* are used instead of the decimal/grouping separators.
* <tr style="vertical-align:top">
* <th scope="row">{@code '}
* <td>Prefix or suffix
* <td>No
* <td>Used to quote special characters in a prefix or suffix,
* for example, {@code "'#'#"} formats 123 to
* {@code "#123"}. To create a single quote
* itself, use two in a row: {@code "# o''clock"}.
* </tbody>
* </table>
* </blockquote>
*
* <h3>Scientific Notation</h3>
*
* <p>Numbers in scientific notation are expressed as the product of a mantissa
* and a power of ten, for example, 1234 can be expressed as 1.234 x 10^3. The
* mantissa is often in the range 1.0 ≤ x {@literal <} 10.0, but it need not
* be.
* {@code DecimalFormat} can be instructed to format and parse scientific
* notation <em>only via a pattern</em>; there is currently no factory method
* that creates a scientific notation format. In a pattern, the exponent
* character immediately followed by one or more digit characters indicates
* scientific notation. Example: {@code "0.###E0"} formats the number
* 1234 as {@code "1.234E3"}.
*
* <ul>
* <li>The number of digit characters after the exponent character gives the
* minimum exponent digit count. There is no maximum. Negative exponents are
* formatted using the localized minus sign, <em>not</em> the prefix and suffix
* from the pattern. This allows patterns such as {@code "0.###E0 m/s"}.
*
* <li>The minimum and maximum number of integer digits are interpreted
* together:
*
* <ul>
* <li>If the maximum number of integer digits is greater than their minimum number
* and greater than 1, it forces the exponent to be a multiple of the maximum
* number of integer digits, and the minimum number of integer digits to be
* interpreted as 1. The most common use of this is to generate
* <em>engineering notation</em>, in which the exponent is a multiple of three,
* e.g., {@code "##0.#####E0"}. Using this pattern, the number 12345
* formats to {@code "12.345E3"}, and 123456 formats to
* {@code "123.456E3"}.
*
* <li>Otherwise, the minimum number of integer digits is achieved by adjusting the
* exponent. Example: 0.00123 formatted with {@code "00.###E0"} yields
* {@code "12.3E-4"}.
* </ul>
*
* <li>The number of significant digits in the mantissa is the sum of the
* <em>minimum integer</em> and <em>maximum fraction</em> digits, and is
* unaffected by the maximum integer digits. For example, 12345 formatted with
* {@code "##0.##E0"} is {@code "12.3E3"}. To show all digits, set
* the significant digits count to zero. The number of significant digits
* does not affect parsing.
*
* <li>Exponential patterns may not contain grouping separators.
* </ul>
*
* <h3>Rounding</h3>
*
* {@code DecimalFormat} provides rounding modes defined in
* {@link java.math.RoundingMode} for formatting. By default, it uses
* {@link java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}.
*
* <h3>Digits</h3>
*
* For formatting, {@code DecimalFormat} uses the ten consecutive
* characters starting with the localized zero digit defined in the
* {@code DecimalFormatSymbols} object as digits. For parsing, these
* digits as well as all Unicode decimal digits, as defined by
* {@link Character#digit Character.digit}, are recognized.
*
* <h4>Special Values</h4>
*
* <p>{@code NaN} is formatted as a string, which typically has a single character
* {@code \uFFFD}. This string is determined by the
* {@code DecimalFormatSymbols} object. This is the only value for which
* the prefixes and suffixes are not used.
*
* <p>Infinity is formatted as a string, which typically has a single character
* {@code \u221E}, with the positive or negative prefixes and suffixes
* applied. The infinity string is determined by the
* {@code DecimalFormatSymbols} object.
*
* <p>Negative zero ({@code "-0"}) parses to
* <ul>
* <li>{@code BigDecimal(0)} if {@code isParseBigDecimal()} is
* true,
* <li>{@code Long(0)} if {@code isParseBigDecimal()} is false
* and {@code isParseIntegerOnly()} is true,
* <li>{@code Double(-0.0)} if both {@code isParseBigDecimal()}
* and {@code isParseIntegerOnly()} are false.
* </ul>
*
* <h3><a id="synchronization">Synchronization</a></h3>
*
* <p>
* Decimal formats are generally not synchronized.
* It is recommended to create separate format instances for each thread.
* If multiple threads access a format concurrently, it must be synchronized
* externally.
*
* <h3>Example</h3>
*
* <blockquote><pre><strong>{@code
* // Print out a number using the localized number, integer, currency,
* // and percent format for each locale}</strong>{@code
* Locale[] locales = NumberFormat.getAvailableLocales();
* double myNumber = -1234.56;
* NumberFormat form;
* for (int j = 0; j < 4; ++j) {
* System.out.println("FORMAT");
* for (int i = 0; i < locales.length; ++i) {
* if (locales[i].getCountry().length() == 0) {
* continue; // Skip language-only locales
* }
* System.out.print(locales[i].getDisplayName());
* switch (j) {
* case 0:
* form = NumberFormat.getInstance(locales[i]); break;
* case 1:
* form = NumberFormat.getIntegerInstance(locales[i]); break;
* case 2:
* form = NumberFormat.getCurrencyInstance(locales[i]); break;
* default:
* form = NumberFormat.getPercentInstance(locales[i]); break;
* }
* if (form instanceof DecimalFormat) {
* System.out.print(": " + ((DecimalFormat) form).toPattern());
* }
* System.out.print(" -> " + form.format(myNumber));
* try {
* System.out.println(" -> " + form.parse(form.format(myNumber)));
* } catch (ParseException e) {}
* }
* }
* }</pre></blockquote>
*
* @see <a href="http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html">Java Tutorial</a>
* @see NumberFormat
* @see DecimalFormatSymbols
* @see ParsePosition
* @author Mark Davis
* @author Alan Liu
* @since 1.1
*/
public class DecimalFormat extends NumberFormat {
/**
* Creates a DecimalFormat using the default pattern and symbols
* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
* This is a convenient way to obtain a
* DecimalFormat when internationalization is not the main concern.
* <p>
* To obtain standard formats for a given locale, use the factory methods
* on NumberFormat such as getNumberInstance. These factories will
* return the most appropriate sub-class of NumberFormat for a given
* locale.
*
* @see java.text.NumberFormat#getInstance
* @see java.text.NumberFormat#getNumberInstance
* @see java.text.NumberFormat#getCurrencyInstance
* @see java.text.NumberFormat#getPercentInstance
*/
public DecimalFormat() {
// Get the pattern for the default locale.
Locale def = Locale.getDefault(Locale.Category.FORMAT);
LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(NumberFormatProvider.class, def);
if (!(adapter instanceof ResourceBundleBasedAdapter)) {
adapter = LocaleProviderAdapter.getResourceBundleBased();
}
String[] all = adapter.getLocaleResources(def).getNumberPatterns();
// Always applyPattern after the symbols are set
this.symbols = DecimalFormatSymbols.getInstance(def);
applyPattern(all[0], false);
}
/**
* Creates a DecimalFormat using the given pattern and the symbols
* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
* This is a convenient way to obtain a
* DecimalFormat when internationalization is not the main concern.
* <p>
* To obtain standard formats for a given locale, use the factory methods
* on NumberFormat such as getNumberInstance. These factories will
* return the most appropriate sub-class of NumberFormat for a given
* locale.
*
* @param pattern a non-localized pattern string.
* @throws NullPointerException if {@code pattern} is null
* @throws IllegalArgumentException if the given pattern is invalid.
* @see java.text.NumberFormat#getInstance
* @see java.text.NumberFormat#getNumberInstance
* @see java.text.NumberFormat#getCurrencyInstance
* @see java.text.NumberFormat#getPercentInstance
*/
public DecimalFormat(String pattern) {
// Always applyPattern after the symbols are set
this.symbols = DecimalFormatSymbols.getInstance(Locale.getDefault(Locale.Category.FORMAT));
applyPattern(pattern, false);
}
/**
* Creates a DecimalFormat using the given pattern and symbols.
* Use this constructor when you need to completely customize the
* behavior of the format.
* <p>
* To obtain standard formats for a given
* locale, use the factory methods on NumberFormat such as
* getInstance or getCurrencyInstance. If you need only minor adjustments
* to a standard format, you can modify the format returned by
* a NumberFormat factory method.
*
* @param pattern a non-localized pattern string
* @param symbols the set of symbols to be used
* @throws NullPointerException if any of the given arguments is null
* @throws IllegalArgumentException if the given pattern is invalid
* @see java.text.NumberFormat#getInstance
* @see java.text.NumberFormat#getNumberInstance
* @see java.text.NumberFormat#getCurrencyInstance
* @see java.text.NumberFormat#getPercentInstance
* @see java.text.DecimalFormatSymbols
*/
public DecimalFormat (String pattern, DecimalFormatSymbols symbols) {
// Always applyPattern after the symbols are set
this.symbols = (DecimalFormatSymbols)symbols.clone();
applyPattern(pattern, false);
}
// Overrides
/**
* Formats a number and appends the resulting text to the given string
* buffer.
* The number can be of any subclass of {@link java.lang.Number}.
* <p>
* This implementation uses the maximum precision permitted.
* @param number the number to format
* @param toAppendTo the {@code StringBuffer} to which the formatted
* text is to be appended
* @param pos keeps track on the position of the field within the
* returned string. For example, for formatting a number
* {@code 1234567.89} in {@code Locale.US} locale,
* if the given {@code fieldPosition} is
* {@link NumberFormat#INTEGER_FIELD}, the begin index
* and end index of {@code fieldPosition} will be set
* to 0 and 9, respectively for the output string
* {@code 1,234,567.89}.
* @return the value passed in as {@code toAppendTo}
* @throws IllegalArgumentException if {@code number} is
* null or not an instance of {@code Number}.
* @throws NullPointerException if {@code toAppendTo} or
* {@code pos} is null
* @throws ArithmeticException if rounding is needed with rounding
* mode being set to RoundingMode.UNNECESSARY
* @see java.text.FieldPosition
*/
@Override
public final StringBuffer format(Object number,
StringBuffer toAppendTo,
FieldPosition pos) {
if (number instanceof Long || number instanceof Integer ||
number instanceof Short || number instanceof Byte ||
number instanceof AtomicInteger ||
number instanceof AtomicLong ||
(number instanceof BigInteger &&
((BigInteger)number).bitLength () < 64)) {
return format(((Number)number).longValue(), toAppendTo, pos);
} else if (number instanceof BigDecimal) {
return format((BigDecimal)number, toAppendTo, pos);
} else if (number instanceof BigInteger) {
return format((BigInteger)number, toAppendTo, pos);
} else if (number instanceof Number) {
return format(((Number)number).doubleValue(), toAppendTo, pos);
} else {
throw new IllegalArgumentException("Cannot format given Object as a Number");
}
}
/**
* Formats a double to produce a string.
* @param number The double to format
* @param result where the text is to be appended
* @param fieldPosition keeps track on the position of the field within
* the returned string. For example, for formatting
* a number {@code 1234567.89} in {@code Locale.US}
* locale, if the given {@code fieldPosition} is
* {@link NumberFormat#INTEGER_FIELD}, the begin index
* and end index of {@code fieldPosition} will be set
* to 0 and 9, respectively for the output string
* {@code 1,234,567.89}.
* @throws NullPointerException if {@code result} or
* {@code fieldPosition} is {@code null}
* @throws ArithmeticException if rounding is needed with rounding
* mode being set to RoundingMode.UNNECESSARY
* @return The formatted number string
* @see java.text.FieldPosition
*/
@Override
public StringBuffer format(double number, StringBuffer result,
FieldPosition fieldPosition) {
// If fieldPosition is a DontCareFieldPosition instance we can
// try to go to fast-path code.
boolean tryFastPath = false;
if (fieldPosition == DontCareFieldPosition.INSTANCE)
tryFastPath = true;
else {
fieldPosition.setBeginIndex(0);
fieldPosition.setEndIndex(0);
}
if (tryFastPath) {
String tempResult = fastFormat(number);
if (tempResult != null) {
result.append(tempResult);
return result;
}
}
// if fast-path could not work, we fallback to standard code.
return format(number, result, fieldPosition.getFieldDelegate());
}
/**
* Formats a double to produce a string.
* @param number The double to format
* @param result where the text is to be appended
* @param delegate notified of locations of sub fields
* @throws ArithmeticException if rounding is needed with rounding
* mode being set to RoundingMode.UNNECESSARY
* @return The formatted number string
*/
StringBuffer format(double number, StringBuffer result,
FieldDelegate delegate) {
boolean nanOrInfinity = handleNaN(number, result, delegate);
if (nanOrInfinity) {
return result;
}
/* Detecting whether a double is negative is easy with the exception of
* the value -0.0. This is a double which has a zero mantissa (and
* exponent), but a negative sign bit. It is semantically distinct from
* a zero with a positive sign bit, and this distinction is important
* to certain kinds of computations. However, it's a little tricky to
* detect, since (-0.0 == 0.0) and !(-0.0 < 0.0). How then, you may
* ask, does it behave distinctly from +0.0? Well, 1/(-0.0) ==
* -Infinity. Proper detection of -0.0 is needed to deal with the
* issues raised by bugs 4106658, 4106667, and 4147706. Liu 7/6/98.
*/
boolean isNegative = ((number < 0.0) || (number == 0.0 && 1/number < 0.0)) ^ (multiplier < 0);
if (multiplier != 1) {
number *= multiplier;
}
nanOrInfinity = handleInfinity(number, result, delegate, isNegative);
if (nanOrInfinity) {
return result;
}
if (isNegative) {
number = -number;
}
// at this point we are guaranteed a nonnegative finite number.
assert (number >= 0 && !Double.isInfinite(number));
return doubleSubformat(number, result, delegate, isNegative);
}
/**
* Checks if the given {@code number} is {@code Double.NaN}. if yes;
* appends the NaN symbol to the result string. The NaN string is
* determined by the DecimalFormatSymbols object.
* @param number the double number to format
* @param result where the text is to be appended
* @param delegate notified of locations of sub fields
* @return true, if number is a NaN; false otherwise
*/
boolean handleNaN(double number, StringBuffer result,
FieldDelegate delegate) {
if (Double.isNaN(number)
|| (Double.isInfinite(number) && multiplier == 0)) {
int iFieldStart = result.length();
result.append(symbols.getNaN());
delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
iFieldStart, result.length(), result);
return true;
}
return false;
}
/**
* Checks if the given {@code number} is {@code Double.NEGATIVE_INFINITY}
* or {@code Double.POSITIVE_INFINITY}. if yes;
* appends the infinity string to the result string. The infinity string is
* determined by the DecimalFormatSymbols object.
* @param number the double number to format
* @param result where the text is to be appended
* @param delegate notified of locations of sub fields
* @param isNegative whether the given {@code number} is negative
* @return true, if number is a {@code Double.NEGATIVE_INFINITY} or
* {@code Double.POSITIVE_INFINITY}; false otherwise
*/
boolean handleInfinity(double number, StringBuffer result,
FieldDelegate delegate, boolean isNegative) {
if (Double.isInfinite(number)) {
if (isNegative) {
append(result, negativePrefix, delegate,
getNegativePrefixFieldPositions(), Field.SIGN);
} else {
append(result, positivePrefix, delegate,
getPositivePrefixFieldPositions(), Field.SIGN);
}
int iFieldStart = result.length();
result.append(symbols.getInfinity());
delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
iFieldStart, result.length(), result);
if (isNegative) {
append(result, negativeSuffix, delegate,
getNegativeSuffixFieldPositions(), Field.SIGN);
} else {
append(result, positiveSuffix, delegate,
getPositiveSuffixFieldPositions(), Field.SIGN);
}
return true;
}
return false;
}
StringBuffer doubleSubformat(double number, StringBuffer result,
FieldDelegate delegate, boolean isNegative) {
synchronized (digitList) {
int maxIntDigits = super.getMaximumIntegerDigits();
int minIntDigits = super.getMinimumIntegerDigits();
int maxFraDigits = super.getMaximumFractionDigits();
int minFraDigits = super.getMinimumFractionDigits();
digitList.set(isNegative, number, useExponentialNotation
? maxIntDigits + maxFraDigits : maxFraDigits,
!useExponentialNotation);
return subformat(result, delegate, isNegative, false,
maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
}
}
/**
* Format a long to produce a string.
* @param number The long to format
* @param result where the text is to be appended
* @param fieldPosition keeps track on the position of the field within
* the returned string. For example, for formatting
* a number {@code 123456789} in {@code Locale.US}
* locale, if the given {@code fieldPosition} is
* {@link NumberFormat#INTEGER_FIELD}, the begin index
* and end index of {@code fieldPosition} will be set
* to 0 and 11, respectively for the output string
* {@code 123,456,789}.
* @throws NullPointerException if {@code result} or
* {@code fieldPosition} is {@code null}
* @throws ArithmeticException if rounding is needed with rounding
* mode being set to RoundingMode.UNNECESSARY
* @return The formatted number string
* @see java.text.FieldPosition
*/
@Override
public StringBuffer format(long number, StringBuffer result,
FieldPosition fieldPosition) {
fieldPosition.setBeginIndex(0);
fieldPosition.setEndIndex(0);
return format(number, result, fieldPosition.getFieldDelegate());
}
/**
* Format a long to produce a string.
* @param number The long to format
* @param result where the text is to be appended
* @param delegate notified of locations of sub fields
* @return The formatted number string
* @throws ArithmeticException if rounding is needed with rounding
* mode being set to RoundingMode.UNNECESSARY
* @see java.text.FieldPosition
*/
StringBuffer format(long number, StringBuffer result,
FieldDelegate delegate) {
boolean isNegative = (number < 0);
if (isNegative) {
number = -number;
}
// In general, long values always represent real finite numbers, so
// we don't have to check for +/- Infinity or NaN. However, there
// is one case we have to be careful of: The multiplier can push
// a number near MIN_VALUE or MAX_VALUE outside the legal range. We
// check for this before multiplying, and if it happens we use
// BigInteger instead.
boolean useBigInteger = false;
if (number < 0) { // This can only happen if number == Long.MIN_VALUE.
if (multiplier != 0) {
useBigInteger = true;
}
} else if (multiplier != 1 && multiplier != 0) {
long cutoff = Long.MAX_VALUE / multiplier;
if (cutoff < 0) {
cutoff = -cutoff;
}
useBigInteger = (number > cutoff);
}
if (useBigInteger) {
if (isNegative) {
number = -number;
}
BigInteger bigIntegerValue = BigInteger.valueOf(number);
return format(bigIntegerValue, result, delegate, true);
}
number *= multiplier;
if (number == 0) {
isNegative = false;
} else {
if (multiplier < 0) {
number = -number;
isNegative = !isNegative;
}
}
synchronized(digitList) {
int maxIntDigits = super.getMaximumIntegerDigits();
int minIntDigits = super.getMinimumIntegerDigits();
int maxFraDigits = super.getMaximumFractionDigits();
int minFraDigits = super.getMinimumFractionDigits();
digitList.set(isNegative, number,
useExponentialNotation ? maxIntDigits + maxFraDigits : 0);
return subformat(result, delegate, isNegative, true,
maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
}
}
/**
* Formats a BigDecimal to produce a string.
* @param number The BigDecimal to format
* @param result where the text is to be appended
* @param fieldPosition keeps track on the position of the field within
* the returned string. For example, for formatting
* a number {@code 1234567.89} in {@code Locale.US}
* locale, if the given {@code fieldPosition} is
* {@link NumberFormat#INTEGER_FIELD}, the begin index
* and end index of {@code fieldPosition} will be set
* to 0 and 9, respectively for the output string
* {@code 1,234,567.89}.
* @return The formatted number string
* @throws ArithmeticException if rounding is needed with rounding
* mode being set to RoundingMode.UNNECESSARY
* @see java.text.FieldPosition
*/
private StringBuffer format(BigDecimal number, StringBuffer result,
FieldPosition fieldPosition) {
fieldPosition.setBeginIndex(0);
fieldPosition.setEndIndex(0);
return format(number, result, fieldPosition.getFieldDelegate());
}
/**
* Formats a BigDecimal to produce a string.
* @param number The BigDecimal to format
* @param result where the text is to be appended
* @param delegate notified of locations of sub fields
* @throws ArithmeticException if rounding is needed with rounding
* mode being set to RoundingMode.UNNECESSARY
* @return The formatted number string
*/
StringBuffer format(BigDecimal number, StringBuffer result,
FieldDelegate delegate) {
if (multiplier != 1) {
number = number.multiply(getBigDecimalMultiplier());
}
boolean isNegative = number.signum() == -1;
if (isNegative) {
number = number.negate();
}
synchronized(digitList) {
int maxIntDigits = getMaximumIntegerDigits();
int minIntDigits = getMinimumIntegerDigits();
int maxFraDigits = getMaximumFractionDigits();
int minFraDigits = getMinimumFractionDigits();
int maximumDigits = maxIntDigits + maxFraDigits;
digitList.set(isNegative, number, useExponentialNotation ?
((maximumDigits < 0) ? Integer.MAX_VALUE : maximumDigits) :
maxFraDigits, !useExponentialNotation);
return subformat(result, delegate, isNegative, false,
maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
}
}
/**
* Format a BigInteger to produce a string.
* @param number The BigInteger to format
* @param result where the text is to be appended
* @param fieldPosition keeps track on the position of the field within
* the returned string. For example, for formatting
* a number {@code 123456789} in {@code Locale.US}
* locale, if the given {@code fieldPosition} is
* {@link NumberFormat#INTEGER_FIELD}, the begin index
* and end index of {@code fieldPosition} will be set
* to 0 and 11, respectively for the output string
* {@code 123,456,789}.
* @return The formatted number string
* @throws ArithmeticException if rounding is needed with rounding
* mode being set to RoundingMode.UNNECESSARY
* @see java.text.FieldPosition
*/
private StringBuffer format(BigInteger number, StringBuffer result,
FieldPosition fieldPosition) {
fieldPosition.setBeginIndex(0);
fieldPosition.setEndIndex(0);
return format(number, result, fieldPosition.getFieldDelegate(), false);
}
/**
* Format a BigInteger to produce a string.
* @param number The BigInteger to format
* @param result where the text is to be appended
* @param delegate notified of locations of sub fields
* @return The formatted number string
* @throws ArithmeticException if rounding is needed with rounding
* mode being set to RoundingMode.UNNECESSARY
* @see java.text.FieldPosition
*/
StringBuffer format(BigInteger number, StringBuffer result,
FieldDelegate delegate, boolean formatLong) {
if (multiplier != 1) {
number = number.multiply(getBigIntegerMultiplier());
}
boolean isNegative = number.signum() == -1;
if (isNegative) {
number = number.negate();
}
synchronized(digitList) {
int maxIntDigits, minIntDigits, maxFraDigits, minFraDigits, maximumDigits;
if (formatLong) {
maxIntDigits = super.getMaximumIntegerDigits();
minIntDigits = super.getMinimumIntegerDigits();
maxFraDigits = super.getMaximumFractionDigits();
minFraDigits = super.getMinimumFractionDigits();
maximumDigits = maxIntDigits + maxFraDigits;
} else {
maxIntDigits = getMaximumIntegerDigits();
minIntDigits = getMinimumIntegerDigits();
maxFraDigits = getMaximumFractionDigits();
minFraDigits = getMinimumFractionDigits();
maximumDigits = maxIntDigits + maxFraDigits;
if (maximumDigits < 0) {
maximumDigits = Integer.MAX_VALUE;
}
}
digitList.set(isNegative, number,
useExponentialNotation ? maximumDigits : 0);
return subformat(result, delegate, isNegative, true,
maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
}
}
/**
* Formats an Object producing an {@code AttributedCharacterIterator}.
* You can use the returned {@code AttributedCharacterIterator}
* to build the resulting String, as well as to determine information
* about the resulting String.
* <p>
* Each attribute key of the AttributedCharacterIterator will be of type
* {@code NumberFormat.Field}, with the attribute value being the
* same as the attribute key.
*
* @throws NullPointerException if obj is null.
* @throws IllegalArgumentException when the Format cannot format the
* given object.
* @throws ArithmeticException if rounding is needed with rounding
* mode being set to RoundingMode.UNNECESSARY
* @param obj The object to format
* @return AttributedCharacterIterator describing the formatted value.
* @since 1.4
*/
@Override
public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
CharacterIteratorFieldDelegate delegate =
new CharacterIteratorFieldDelegate();
StringBuffer sb = new StringBuffer();
if (obj instanceof Double || obj instanceof Float) {
format(((Number)obj).doubleValue(), sb, delegate);
} else if (obj instanceof Long || obj instanceof Integer ||
obj instanceof Short || obj instanceof Byte ||
obj instanceof AtomicInteger || obj instanceof AtomicLong) {
format(((Number)obj).longValue(), sb, delegate);
} else if (obj instanceof BigDecimal) {
format((BigDecimal)obj, sb, delegate);
} else if (obj instanceof BigInteger) {
format((BigInteger)obj, sb, delegate, false);
} else if (obj == null) {
throw new NullPointerException(
"formatToCharacterIterator must be passed non-null object");
} else {
throw new IllegalArgumentException(
"Cannot format given Object as a Number");
}
return delegate.getIterator(sb.toString());
}
// ==== Begin fast-path formatting logic for double =========================
/* Fast-path formatting will be used for format(double ...) methods iff a
* number of conditions are met (see checkAndSetFastPathStatus()):
* - Only if instance properties meet the right predefined conditions.
* - The abs value of the double to format is <= Integer.MAX_VALUE.
*
* The basic approach is to split the binary to decimal conversion of a
* double value into two phases:
* * The conversion of the integer portion of the double.
* * The conversion of the fractional portion of the double
* (limited to two or three digits).
*
* The isolation and conversion of the integer portion of the double is
* straightforward. The conversion of the fraction is more subtle and relies
* on some rounding properties of double to the decimal precisions in
* question. Using the terminology of BigDecimal, this fast-path algorithm
* is applied when a double value has a magnitude less than Integer.MAX_VALUE
* and rounding is to nearest even and the destination format has two or
* three digits of *scale* (digits after the decimal point).
*
* Under a rounding to nearest even policy, the returned result is a digit
* string of a number in the (in this case decimal) destination format
* closest to the exact numerical value of the (in this case binary) input
* value. If two destination format numbers are equally distant, the one
* with the last digit even is returned. To compute such a correctly rounded
* value, some information about digits beyond the smallest returned digit
* position needs to be consulted.
*
* In general, a guard digit, a round digit, and a sticky *bit* are needed
* beyond the returned digit position. If the discarded portion of the input
* is sufficiently large, the returned digit string is incremented. In round
* to nearest even, this threshold to increment occurs near the half-way
* point between digits. The sticky bit records if there are any remaining
* trailing digits of the exact input value in the new format; the sticky bit
* is consulted only in close to half-way rounding cases.
*
* Given the computation of the digit and bit values, rounding is then
* reduced to a table lookup problem. For decimal, the even/odd cases look
* like this:
*
* Last Round Sticky
* 6 5 0 => 6 // exactly halfway, return even digit.
* 6 5 1 => 7 // a little bit more than halfway, round up.
* 7 5 0 => 8 // exactly halfway, round up to even.
* 7 5 1 => 8 // a little bit more than halfway, round up.
* With analogous entries for other even and odd last-returned digits.
*
* However, decimal negative powers of 5 smaller than 0.5 are *not* exactly
* representable as binary fraction. In particular, 0.005 (the round limit
* for a two-digit scale) and 0.0005 (the round limit for a three-digit
* scale) are not representable. Therefore, for input values near these cases
* the sticky bit is known to be set which reduces the rounding logic to:
*
* Last Round Sticky
* 6 5 1 => 7 // a little bit more than halfway, round up.
* 7 5 1 => 8 // a little bit more than halfway, round up.
*
* In other words, if the round digit is 5, the sticky bit is known to be
* set. If the round digit is something other than 5, the sticky bit is not
* relevant. Therefore, some of the logic about whether or not to increment
* the destination *decimal* value can occur based on tests of *binary*
* computations of the binary input number.
*/
/**
* Check validity of using fast-path for this instance. If fast-path is valid
* for this instance, sets fast-path state as true and initializes fast-path
* utility fields as needed.
*
* This method is supposed to be called rarely, otherwise that will break the
* fast-path performance. That means avoiding frequent changes of the
* properties of the instance, since for most properties, each time a change
* happens, a call to this method is needed at the next format call.
*
* FAST-PATH RULES:
* Similar to the default DecimalFormat instantiation case.
* More precisely:
* - HALF_EVEN rounding mode,
* - isGroupingUsed() is true,
* - groupingSize of 3,
* - multiplier is 1,
* - Decimal separator not mandatory,
* - No use of exponential notation,
* - minimumIntegerDigits is exactly 1 and maximumIntegerDigits at least 10
* - For number of fractional digits, the exact values found in the default case:
* Currency : min = max = 2.
* Decimal : min = 0. max = 3.
*
*/
private boolean checkAndSetFastPathStatus() {
boolean fastPathWasOn = isFastPath;
if ((roundingMode == RoundingMode.HALF_EVEN) &&
(isGroupingUsed()) &&
(groupingSize == 3) &&
(multiplier == 1) &&
(!decimalSeparatorAlwaysShown) &&
(!useExponentialNotation)) {
// The fast-path algorithm is semi-hardcoded against
// minimumIntegerDigits and maximumIntegerDigits.
isFastPath = ((minimumIntegerDigits == 1) &&
(maximumIntegerDigits >= 10));
// The fast-path algorithm is hardcoded against
// minimumFractionDigits and maximumFractionDigits.
if (isFastPath) {
if (isCurrencyFormat) {
if ((minimumFractionDigits != 2) ||
(maximumFractionDigits != 2))
isFastPath = false;
} else if ((minimumFractionDigits != 0) ||
(maximumFractionDigits != 3))
isFastPath = false;
}
} else
isFastPath = false;
resetFastPathData(fastPathWasOn);
fastPathCheckNeeded = false;
/*
* Returns true after successfully checking the fast path condition and
* setting the fast path data. The return value is used by the
* fastFormat() method to decide whether to call the resetFastPathData
* method to reinitialize fast path data or is it already initialized
* in this method.
*/
return true;
}
private void resetFastPathData(boolean fastPathWasOn) {
// Since some instance properties may have changed while still falling
// in the fast-path case, we need to reinitialize fastPathData anyway.
if (isFastPath) {
// We need to instantiate fastPathData if not already done.
if (fastPathData == null) {
fastPathData = new FastPathData();
}
// Sets up the locale specific constants used when formatting.
// '0' is our default representation of zero.
fastPathData.zeroDelta = symbols.getZeroDigit() - '0';
fastPathData.groupingChar = isCurrencyFormat ?
symbols.getMonetaryGroupingSeparator() :
symbols.getGroupingSeparator();
// Sets up fractional constants related to currency/decimal pattern.
fastPathData.fractionalMaxIntBound = (isCurrencyFormat)
? 99 : 999;
fastPathData.fractionalScaleFactor = (isCurrencyFormat)
? 100.0d : 1000.0d;
// Records the need for adding prefix or suffix
fastPathData.positiveAffixesRequired
= !positivePrefix.isEmpty() || !positiveSuffix.isEmpty();
fastPathData.negativeAffixesRequired
= !negativePrefix.isEmpty() || !negativeSuffix.isEmpty();
// Creates a cached char container for result, with max possible size.
int maxNbIntegralDigits = 10;
int maxNbGroups = 3;
int containerSize
= Math.max(positivePrefix.length(), negativePrefix.length())
+ maxNbIntegralDigits + maxNbGroups + 1
+ maximumFractionDigits
+ Math.max(positiveSuffix.length(), negativeSuffix.length());
fastPathData.fastPathContainer = new char[containerSize];
// Sets up prefix and suffix char arrays constants.
fastPathData.charsPositiveSuffix = positiveSuffix.toCharArray();
fastPathData.charsNegativeSuffix = negativeSuffix.toCharArray();
fastPathData.charsPositivePrefix = positivePrefix.toCharArray();
fastPathData.charsNegativePrefix = negativePrefix.toCharArray();
// Sets up fixed index positions for integral and fractional digits.
// Sets up decimal point in cached result container.
int longestPrefixLength
= Math.max(positivePrefix.length(),
negativePrefix.length());
int decimalPointIndex
= maxNbIntegralDigits + maxNbGroups + longestPrefixLength;
fastPathData.integralLastIndex = decimalPointIndex - 1;
fastPathData.fractionalFirstIndex = decimalPointIndex + 1;
fastPathData.fastPathContainer[decimalPointIndex]
= isCurrencyFormat
? symbols.getMonetaryDecimalSeparator()
: symbols.getDecimalSeparator();
} else if (fastPathWasOn) {
// Previous state was fast-path and is no more.
// Resets cached array constants.
fastPathData.fastPathContainer = null;
fastPathData.charsPositiveSuffix = null;
fastPathData.charsNegativeSuffix = null;
fastPathData.charsPositivePrefix = null;
fastPathData.charsNegativePrefix = null;
}
}
/**
* Returns true if rounding-up must be done on {@code scaledFractionalPartAsInt},
* false otherwise.
*
* This is a utility method that takes correct half-even rounding decision on
* passed fractional value at the scaled decimal point (2 digits for currency
* case and 3 for decimal case), when the approximated fractional part after
* scaled decimal point is exactly 0.5d. This is done by means of exact
* calculations on the {@code fractionalPart} floating-point value.
*
* This method is supposed to be called by private {@code fastDoubleFormat}
* method only.
*
* The algorithms used for the exact calculations are :
*
* The <b><i>FastTwoSum</i></b> algorithm, from T.J.Dekker, described in the
* papers "<i>A Floating-Point Technique for Extending the Available
* Precision</i>" by Dekker, and in "<i>Adaptive Precision Floating-Point
* Arithmetic and Fast Robust Geometric Predicates</i>" from J.Shewchuk.
*
* A modified version of <b><i>Sum2S</i></b> cascaded summation described in
* "<i>Accurate Sum and Dot Product</i>" from Takeshi Ogita and All. As
* Ogita says in this paper this is an equivalent of the Kahan-Babuska's
* summation algorithm because we order the terms by magnitude before summing
* them. For this reason we can use the <i>FastTwoSum</i> algorithm rather
* than the more expensive Knuth's <i>TwoSum</i>.
*
* We do this to avoid a more expensive exact "<i>TwoProduct</i>" algorithm,
* like those described in Shewchuk's paper above. See comments in the code
* below.
*
* @param fractionalPart The fractional value on which we take rounding
* decision.
* @param scaledFractionalPartAsInt The integral part of the scaled
* fractional value.
*
* @return the decision that must be taken regarding half-even rounding.
*/
private boolean exactRoundUp(double fractionalPart,
int scaledFractionalPartAsInt) {
/* exactRoundUp() method is called by fastDoubleFormat() only.
* The precondition expected to be verified by the passed parameters is :
* scaledFractionalPartAsInt ==
* (int) (fractionalPart * fastPathData.fractionalScaleFactor).
* This is ensured by fastDoubleFormat() code.
*/
/* We first calculate roundoff error made by fastDoubleFormat() on
* the scaled fractional part. We do this with exact calculation on the
* passed fractionalPart. Rounding decision will then be taken from roundoff.
*/
/* ---- TwoProduct(fractionalPart, scale factor (i.e. 1000.0d or 100.0d)).
*
* The below is an optimized exact "TwoProduct" calculation of passed
* fractional part with scale factor, using Ogita's Sum2S cascaded
* summation adapted as Kahan-Babuska equivalent by using FastTwoSum
* (much faster) rather than Knuth's TwoSum.
*
* We can do this because we order the summation from smallest to
* greatest, so that FastTwoSum can be used without any additional error.
*
* The "TwoProduct" exact calculation needs 17 flops. We replace this by
* a cascaded summation of FastTwoSum calculations, each involving an
* exact multiply by a power of 2.
*
* Doing so saves overall 4 multiplications and 1 addition compared to
* using traditional "TwoProduct".
*
* The scale factor is either 100 (currency case) or 1000 (decimal case).
* - when 1000, we replace it by (1024 - 16 - 8) = 1000.
* - when 100, we replace it by (128 - 32 + 4) = 100.
* Every multiplication by a power of 2 (1024, 128, 32, 16, 8, 4) is exact.
*
*/
double approxMax; // Will always be positive.
double approxMedium; // Will always be negative.
double approxMin;
double fastTwoSumApproximation = 0.0d;
double fastTwoSumRoundOff = 0.0d;
double bVirtual = 0.0d;
if (isCurrencyFormat) {
// Scale is 100 = 128 - 32 + 4.
// Multiply by 2**n is a shift. No roundoff. No error.
approxMax = fractionalPart * 128.00d;
approxMedium = - (fractionalPart * 32.00d);
approxMin = fractionalPart * 4.00d;
} else {
// Scale is 1000 = 1024 - 16 - 8.
// Multiply by 2**n is a shift. No roundoff. No error.
approxMax = fractionalPart * 1024.00d;
approxMedium = - (fractionalPart * 16.00d);
approxMin = - (fractionalPart * 8.00d);
}
// Shewchuk/Dekker's FastTwoSum(approxMedium, approxMin).
assert(-approxMedium >= Math.abs(approxMin));
fastTwoSumApproximation = approxMedium + approxMin;
bVirtual = fastTwoSumApproximation - approxMedium;
fastTwoSumRoundOff = approxMin - bVirtual;
double approxS1 = fastTwoSumApproximation;
double roundoffS1 = fastTwoSumRoundOff;
// Shewchuk/Dekker's FastTwoSum(approxMax, approxS1);
assert(approxMax >= Math.abs(approxS1));
fastTwoSumApproximation = approxMax + approxS1;
bVirtual = fastTwoSumApproximation - approxMax;
fastTwoSumRoundOff = approxS1 - bVirtual;
double roundoff1000 = fastTwoSumRoundOff;
double approx1000 = fastTwoSumApproximation;
double roundoffTotal = roundoffS1 + roundoff1000;
// Shewchuk/Dekker's FastTwoSum(approx1000, roundoffTotal);
assert(approx1000 >= Math.abs(roundoffTotal));
fastTwoSumApproximation = approx1000 + roundoffTotal;
bVirtual = fastTwoSumApproximation - approx1000;
// Now we have got the roundoff for the scaled fractional
double scaledFractionalRoundoff = roundoffTotal - bVirtual;
// ---- TwoProduct(fractionalPart, scale (i.e. 1000.0d or 100.0d)) end.
/* ---- Taking the rounding decision
*
* We take rounding decision based on roundoff and half-even rounding
* rule.
*
* The above TwoProduct gives us the exact roundoff on the approximated
* scaled fractional, and we know that this approximation is exactly
* 0.5d, since that has already been tested by the caller
* (fastDoubleFormat).
*
* Decision comes first from the sign of the calculated exact roundoff.
* - Since being exact roundoff, it cannot be positive with a scaled
* fractional less than 0.5d, as well as negative with a scaled
* fractional greater than 0.5d. That leaves us with following 3 cases.
* - positive, thus scaled fractional == 0.500....0fff ==> round-up.
* - negative, thus scaled fractional == 0.499....9fff ==> don't round-up.
* - is zero, thus scaled fractioanl == 0.5 ==> half-even rounding applies :
* we round-up only if the integral part of the scaled fractional is odd.
*
*/
if (scaledFractionalRoundoff > 0.0) {
return true;
} else if (scaledFractionalRoundoff < 0.0) {
return false;
} else if ((scaledFractionalPartAsInt & 1) != 0) {
return true;
}
return false;
// ---- Taking the rounding decision end
}
/**
* Collects integral digits from passed {@code number}, while setting
* grouping chars as needed. Updates {@code firstUsedIndex} accordingly.
*
* Loops downward starting from {@code backwardIndex} position (inclusive).
*
* @param number The int value from which we collect digits.
* @param digitsBuffer The char array container where digits and grouping chars
* are stored.
* @param backwardIndex the position from which we start storing digits in
* digitsBuffer.
*
*/
private void collectIntegralDigits(int number,
char[] digitsBuffer,
int backwardIndex) {
int index = backwardIndex;
int q;
int r;
while (number > 999) {
// Generates 3 digits per iteration.
q = number / 1000;
r = number - (q << 10) + (q << 4) + (q << 3); // -1024 +16 +8 = 1000.
number = q;
digitsBuffer[index--] = DigitArrays.DigitOnes1000[r];
digitsBuffer[index--] = DigitArrays.DigitTens1000[r];
digitsBuffer[index--] = DigitArrays.DigitHundreds1000[r];
digitsBuffer[index--] = fastPathData.groupingChar;
}
// Collects last 3 or less digits.
digitsBuffer[index] = DigitArrays.DigitOnes1000[number];
if (number > 9) {
digitsBuffer[--index] = DigitArrays.DigitTens1000[number];
if (number > 99)
digitsBuffer[--index] = DigitArrays.DigitHundreds1000[number];
}
fastPathData.firstUsedIndex = index;
}
/**
* Collects the 2 (currency) or 3 (decimal) fractional digits from passed
* {@code number}, starting at {@code startIndex} position
* inclusive. There is no punctuation to set here (no grouping chars).
* Updates {@code fastPathData.lastFreeIndex} accordingly.
*
*
* @param number The int value from which we collect digits.
* @param digitsBuffer The char array container where digits are stored.
* @param startIndex the position from which we start storing digits in
* digitsBuffer.
*
*/
private void collectFractionalDigits(int number,
char[] digitsBuffer,
int startIndex) {
int index = startIndex;
char digitOnes = DigitArrays.DigitOnes1000[number];
char digitTens = DigitArrays.DigitTens1000[number];
if (isCurrencyFormat) {
// Currency case. Always collects fractional digits.
digitsBuffer[index++] = digitTens;
digitsBuffer[index++] = digitOnes;
} else if (number != 0) {
// Decimal case. Hundreds will always be collected
digitsBuffer[index++] = DigitArrays.DigitHundreds1000[number];
// Ending zeros won't be collected.
if (digitOnes != '0') {
digitsBuffer[index++] = digitTens;
digitsBuffer[index++] = digitOnes;
} else if (digitTens != '0')
digitsBuffer[index++] = digitTens;
} else
// This is decimal pattern and fractional part is zero.
// We must remove decimal point from result.
index--;
fastPathData.lastFreeIndex = index;
}
/**
* Internal utility.
* Adds the passed {@code prefix} and {@code suffix} to {@code container}.
*
* @param container Char array container which to prepend/append the
* prefix/suffix.
* @param prefix Char sequence to prepend as a prefix.
* @param suffix Char sequence to append as a suffix.
*
*/
// private void addAffixes(boolean isNegative, char[] container) {
private void addAffixes(char[] container, char[] prefix, char[] suffix) {
// We add affixes only if needed (affix length > 0).
int pl = prefix.length;
int sl = suffix.length;
if (pl != 0) prependPrefix(prefix, pl, container);
if (sl != 0) appendSuffix(suffix, sl, container);
}
/**
* Prepends the passed {@code prefix} chars to given result
* {@code container}. Updates {@code fastPathData.firstUsedIndex}
* accordingly.
*
* @param prefix The prefix characters to prepend to result.
* @param len The number of chars to prepend.
* @param container Char array container which to prepend the prefix
*/
private void prependPrefix(char[] prefix,
int len,
char[] container) {
fastPathData.firstUsedIndex -= len;
int startIndex = fastPathData.firstUsedIndex;
// If prefix to prepend is only 1 char long, just assigns this char.
// If prefix is less or equal 4, we use a dedicated algorithm that
// has shown to run faster than System.arraycopy.
// If more than 4, we use System.arraycopy.
if (len == 1)
container[startIndex] = prefix[0];
else if (len <= 4) {
int dstLower = startIndex;
int dstUpper = dstLower + len - 1;
int srcUpper = len - 1;
container[dstLower] = prefix[0];
container[dstUpper] = prefix[srcUpper];
if (len > 2)
container[++dstLower] = prefix[1];
if (len == 4)
container[--dstUpper] = prefix[2];
} else
System.arraycopy(prefix, 0, container, startIndex, len);
}
/**
* Appends the passed {@code suffix} chars to given result
* {@code container}. Updates {@code fastPathData.lastFreeIndex}
* accordingly.
*
* @param suffix The suffix characters to append to result.
* @param len The number of chars to append.
* @param container Char array container which to append the suffix
*/
private void appendSuffix(char[] suffix,
int len,
char[] container) {
int startIndex = fastPathData.lastFreeIndex;
// If suffix to append is only 1 char long, just assigns this char.
// If suffix is less or equal 4, we use a dedicated algorithm that
// has shown to run faster than System.arraycopy.
// If more than 4, we use System.arraycopy.
if (len == 1)
container[startIndex] = suffix[0];
else if (len <= 4) {
int dstLower = startIndex;
int dstUpper = dstLower + len - 1;
int srcUpper = len - 1;
container[dstLower] = suffix[0];
container[dstUpper] = suffix[srcUpper];
if (len > 2)
container[++dstLower] = suffix[1];
if (len == 4)
container[--dstUpper] = suffix[2];
} else
System.arraycopy(suffix, 0, container, startIndex, len);
fastPathData.lastFreeIndex += len;
}
/**
* Converts digit chars from {@code digitsBuffer} to current locale.
*
* Must be called before adding affixes since we refer to
* {@code fastPathData.firstUsedIndex} and {@code fastPathData.lastFreeIndex},
* and do not support affixes (for speed reason).
*
* We loop backward starting from last used index in {@code fastPathData}.
*
* @param digitsBuffer The char array container where the digits are stored.
*/
private void localizeDigits(char[] digitsBuffer) {
// We will localize only the digits, using the groupingSize,
// and taking into account fractional part.
// First take into account fractional part.
int digitsCounter =
fastPathData.lastFreeIndex - fastPathData.fractionalFirstIndex;
// The case when there is no fractional digits.
if (digitsCounter < 0)
digitsCounter = groupingSize;
// Only the digits remains to localize.
for (int cursor = fastPathData.lastFreeIndex - 1;
cursor >= fastPathData.firstUsedIndex;
cursor--) {
if (digitsCounter != 0) {
// This is a digit char, we must localize it.
digitsBuffer[cursor] += fastPathData.zeroDelta;
digitsCounter--;
} else {
// Decimal separator or grouping char. Reinit counter only.
digitsCounter = groupingSize;
}
}
}
/**
* This is the main entry point for the fast-path format algorithm.
*
* At this point we are sure to be in the expected conditions to run it.
* This algorithm builds the formatted result and puts it in the dedicated
* {@code fastPathData.fastPathContainer}.
*
* @param d the double value to be formatted.
* @param negative Flag precising if {@code d} is negative.
*/
private void fastDoubleFormat(double d,
boolean negative) {
char[] container = fastPathData.fastPathContainer;
/*
* The principle of the algorithm is to :
* - Break the passed double into its integral and fractional parts
* converted into integers.
* - Then decide if rounding up must be applied or not by following
* the half-even rounding rule, first using approximated scaled
* fractional part.
* - For the difficult cases (approximated scaled fractional part
* being exactly 0.5d), we refine the rounding decision by calling
* exactRoundUp utility method that both calculates the exact roundoff
* on the approximation and takes correct rounding decision.
* - We round-up the fractional part if needed, possibly propagating the
* rounding to integral part if we meet a "all-nine" case for the
* scaled fractional part.
* - We then collect digits from the resulting integral and fractional
* parts, also setting the required grouping chars on the fly.
* - Then we localize the collected digits if needed, and
* - Finally prepend/append prefix/suffix if any is needed.
*/
// Exact integral part of d.
int integralPartAsInt = (int) d;
// Exact fractional part of d (since we subtract it's integral part).
double exactFractionalPart = d - (double) integralPartAsInt;
// Approximated scaled fractional part of d (due to multiplication).
double scaledFractional =
exactFractionalPart * fastPathData.fractionalScaleFactor;
// Exact integral part of scaled fractional above.
int fractionalPartAsInt = (int) scaledFractional;
// Exact fractional part of scaled fractional above.
scaledFractional = scaledFractional - (double) fractionalPartAsInt;
// Only when scaledFractional is exactly 0.5d do we have to do exact
// calculations and take fine-grained rounding decision, since
// approximated results above may lead to incorrect decision.
// Otherwise comparing against 0.5d (strictly greater or less) is ok.
boolean roundItUp = false;
if (scaledFractional >= 0.5d) {
if (scaledFractional == 0.5d)
// Rounding need fine-grained decision.
roundItUp = exactRoundUp(exactFractionalPart, fractionalPartAsInt);
else
roundItUp = true;
if (roundItUp) {
// Rounds up both fractional part (and also integral if needed).
if (fractionalPartAsInt < fastPathData.fractionalMaxIntBound) {
fractionalPartAsInt++;
} else {
// Propagates rounding to integral part since "all nines" case.
fractionalPartAsInt = 0;
integralPartAsInt++;
}
}
}
// Collecting digits.
collectFractionalDigits(fractionalPartAsInt, container,
fastPathData.fractionalFirstIndex);
collectIntegralDigits(integralPartAsInt, container,
fastPathData.integralLastIndex);
// Localizing digits.
if (fastPathData.zeroDelta != 0)
localizeDigits(container);
// Adding prefix and suffix.
if (negative) {
if (fastPathData.negativeAffixesRequired)
addAffixes(container,
fastPathData.charsNegativePrefix,
fastPathData.charsNegativeSuffix);
} else if (fastPathData.positiveAffixesRequired)
addAffixes(container,
fastPathData.charsPositivePrefix,
fastPathData.charsPositiveSuffix);
}
/**
* A fast-path shortcut of format(double) to be called by NumberFormat, or by
* format(double, ...) public methods.
*
* If instance can be applied fast-path and passed double is not NaN or
* Infinity, is in the integer range, we call {@code fastDoubleFormat}
* after changing {@code d} to its positive value if necessary.
*
* Otherwise returns null by convention since fast-path can't be exercized.
*
* @param d The double value to be formatted
*
* @return the formatted result for {@code d} as a string.
*/
String fastFormat(double d) {
boolean isDataSet = false;
// (Re-)Evaluates fast-path status if needed.
if (fastPathCheckNeeded) {
isDataSet = checkAndSetFastPathStatus();
}
if (!isFastPath )
// DecimalFormat instance is not in a fast-path state.
return null;
if (!Double.isFinite(d))
// Should not use fast-path for Infinity and NaN.
return null;
// Extracts and records sign of double value, possibly changing it
// to a positive one, before calling fastDoubleFormat().
boolean negative = false;
if (d < 0.0d) {
negative = true;
d = -d;
} else if (d == 0.0d) {
negative = (Math.copySign(1.0d, d) == -1.0d);
d = +0.0d;
}
if (d > MAX_INT_AS_DOUBLE)
// Filters out values that are outside expected fast-path range
return null;
else {
if (!isDataSet) {
/*
* If the fast path data is not set through
* checkAndSetFastPathStatus() and fulfil the
* fast path conditions then reset the data
* directly through resetFastPathData()
*/
resetFastPathData(isFastPath);
}
fastDoubleFormat(d, negative);
}
// Returns a new string from updated fastPathContainer.
return new String(fastPathData.fastPathContainer,
fastPathData.firstUsedIndex,
fastPathData.lastFreeIndex - fastPathData.firstUsedIndex);
}
/**
* Sets the {@code DigitList} used by this {@code DecimalFormat}
* instance.
* @param number the number to format
* @param isNegative true, if the number is negative; false otherwise
* @param maxDigits the max digits
*/
void setDigitList(Number number, boolean isNegative, int maxDigits) {
if (number instanceof Double) {
digitList.set(isNegative, (Double) number, maxDigits, true);
} else if (number instanceof BigDecimal) {
digitList.set(isNegative, (BigDecimal) number, maxDigits, true);
} else if (number instanceof Long) {
digitList.set(isNegative, (Long) number, maxDigits);
} else if (number instanceof BigInteger) {
digitList.set(isNegative, (BigInteger) number, maxDigits);
}
}
// ======== End fast-path formating logic for double =========================
/**
* Complete the formatting of a finite number. On entry, the digitList must
* be filled in with the correct digits.
*/
private StringBuffer subformat(StringBuffer result, FieldDelegate delegate,
boolean isNegative, boolean isInteger,
int maxIntDigits, int minIntDigits,
int maxFraDigits, int minFraDigits) {
// Process prefix
if (isNegative) {
append(result, negativePrefix, delegate,
getNegativePrefixFieldPositions(), Field.SIGN);
} else {
append(result, positivePrefix, delegate,
getPositivePrefixFieldPositions(), Field.SIGN);
}
// Process number
subformatNumber(result, delegate, isNegative, isInteger,
maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
// Process suffix
if (isNegative) {
append(result, negativeSuffix, delegate,
getNegativeSuffixFieldPositions(), Field.SIGN);
} else {
append(result, positiveSuffix, delegate,
getPositiveSuffixFieldPositions(), Field.SIGN);
}
return result;
}
/**
* Subformats number part using the {@code DigitList} of this
* {@code DecimalFormat} instance.
* @param result where the text is to be appended
* @param delegate notified of the location of sub fields
* @param isNegative true, if the number is negative; false otherwise
* @param isInteger true, if the number is an integer; false otherwise
* @param maxIntDigits maximum integer digits
* @param minIntDigits minimum integer digits
* @param maxFraDigits maximum fraction digits
* @param minFraDigits minimum fraction digits
*/
void subformatNumber(StringBuffer result, FieldDelegate delegate,
boolean isNegative, boolean isInteger,
int maxIntDigits, int minIntDigits,
int maxFraDigits, int minFraDigits) {
char grouping = isCurrencyFormat ?
symbols.getMonetaryGroupingSeparator() :
symbols.getGroupingSeparator();
char zero = symbols.getZeroDigit();
int zeroDelta = zero - '0'; // '0' is the DigitList representation of zero
char decimal = isCurrencyFormat ?
symbols.getMonetaryDecimalSeparator() :
symbols.getDecimalSeparator();
/* Per bug 4147706, DecimalFormat must respect the sign of numbers which
* format as zero. This allows sensible computations and preserves
* relations such as signum(1/x) = signum(x), where x is +Infinity or
* -Infinity. Prior to this fix, we always formatted zero values as if
* they were positive. Liu 7/6/98.
*/
if (digitList.isZero()) {
digitList.decimalAt = 0; // Normalize
}
if (useExponentialNotation) {
int iFieldStart = result.length();
int iFieldEnd = -1;
int fFieldStart = -1;
// Minimum integer digits are handled in exponential format by
// adjusting the exponent. For example, 0.01234 with 3 minimum
// integer digits is "123.4E-4".
// Maximum integer digits are interpreted as indicating the
// repeating range. This is useful for engineering notation, in
// which the exponent is restricted to a multiple of 3. For
// example, 0.01234 with 3 maximum integer digits is "12.34e-3".
// If maximum integer digits are > 1 and are larger than
// minimum integer digits, then minimum integer digits are
// ignored.
int exponent = digitList.decimalAt;
int repeat = maxIntDigits;
int minimumIntegerDigits = minIntDigits;
if (repeat > 1 && repeat > minIntDigits) {
// A repeating range is defined; adjust to it as follows.
// If repeat == 3, we have 6,5,4=>3; 3,2,1=>0; 0,-1,-2=>-3;
// -3,-4,-5=>-6, etc. This takes into account that the
// exponent we have here is off by one from what we expect;
// it is for the format 0.MMMMMx10^n.
if (exponent >= 1) {
exponent = ((exponent - 1) / repeat) * repeat;
} else {
// integer division rounds towards 0
exponent = ((exponent - repeat) / repeat) * repeat;
}
minimumIntegerDigits = 1;
} else {
// No repeating range is defined; use minimum integer digits.
exponent -= minimumIntegerDigits;
}
// We now output a minimum number of digits, and more if there
// are more digits, up to the maximum number of digits. We
// place the decimal point after the "integer" digits, which
// are the first (decimalAt - exponent) digits.
int minimumDigits = minIntDigits + minFraDigits;
if (minimumDigits < 0) { // overflow?
minimumDigits = Integer.MAX_VALUE;
}
// The number of integer digits is handled specially if the number
// is zero, since then there may be no digits.
int integerDigits = digitList.isZero() ? minimumIntegerDigits :
digitList.decimalAt - exponent;
if (minimumDigits < integerDigits) {
minimumDigits = integerDigits;
}
int totalDigits = digitList.count;
if (minimumDigits > totalDigits) {
totalDigits = minimumDigits;
}
boolean addedDecimalSeparator = false;
for (int i=0; i<totalDigits; ++i) {
if (i == integerDigits) {
// Record field information for caller.
iFieldEnd = result.length();
result.append(decimal);
addedDecimalSeparator = true;
// Record field information for caller.
fFieldStart = result.length();
}
result.append((i < digitList.count) ?
(char)(digitList.digits[i] + zeroDelta) :
zero);
}
if (decimalSeparatorAlwaysShown && totalDigits == integerDigits) {
// Record field information for caller.
iFieldEnd = result.length();
result.append(decimal);
addedDecimalSeparator = true;
// Record field information for caller.
fFieldStart = result.length();
}
// Record field information
if (iFieldEnd == -1) {
iFieldEnd = result.length();
}
delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
iFieldStart, iFieldEnd, result);
if (addedDecimalSeparator) {
delegate.formatted(Field.DECIMAL_SEPARATOR,
Field.DECIMAL_SEPARATOR,
iFieldEnd, fFieldStart, result);
}
if (fFieldStart == -1) {
fFieldStart = result.length();
}
delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION,
fFieldStart, result.length(), result);
// The exponent is output using the pattern-specified minimum
// exponent digits. There is no maximum limit to the exponent
// digits, since truncating the exponent would result in an
// unacceptable inaccuracy.
int fieldStart = result.length();
result.append(symbols.getExponentSeparator());
delegate.formatted(Field.EXPONENT_SYMBOL, Field.EXPONENT_SYMBOL,
fieldStart, result.length(), result);
// For zero values, we force the exponent to zero. We
// must do this here, and not earlier, because the value
// is used to determine integer digit count above.
if (digitList.isZero()) {
exponent = 0;
}
boolean negativeExponent = exponent < 0;
if (negativeExponent) {
exponent = -exponent;
fieldStart = result.length();
result.append(symbols.getMinusSignText());
delegate.formatted(Field.EXPONENT_SIGN, Field.EXPONENT_SIGN,
fieldStart, result.length(), result);
}
digitList.set(negativeExponent, exponent);
int eFieldStart = result.length();
for (int i=digitList.decimalAt; i<minExponentDigits; ++i) {
result.append(zero);
}
for (int i=0; i<digitList.decimalAt; ++i) {
result.append((i < digitList.count) ?
(char)(digitList.digits[i] + zeroDelta) : zero);
}
delegate.formatted(Field.EXPONENT, Field.EXPONENT, eFieldStart,
result.length(), result);
} else {
int iFieldStart = result.length();
// Output the integer portion. Here 'count' is the total
// number of integer digits we will display, including both
// leading zeros required to satisfy getMinimumIntegerDigits,
// and actual digits present in the number.
int count = minIntDigits;
int digitIndex = 0; // Index into digitList.fDigits[]
if (digitList.decimalAt > 0 && count < digitList.decimalAt) {
count = digitList.decimalAt;
}
// Handle the case where getMaximumIntegerDigits() is smaller
// than the real number of integer digits. If this is so, we
// output the least significant max integer digits. For example,
// the value 1997 printed with 2 max integer digits is just "97".
if (count > maxIntDigits) {
count = maxIntDigits;
digitIndex = digitList.decimalAt - count;
}
int sizeBeforeIntegerPart = result.length();
for (int i=count-1; i>=0; --i) {
if (i < digitList.decimalAt && digitIndex < digitList.count) {
// Output a real digit
result.append((char)(digitList.digits[digitIndex++] + zeroDelta));
} else {
// Output a leading zero
result.append(zero);
}
// Output grouping separator if necessary. Don't output a
// grouping separator if i==0 though; that's at the end of
// the integer part.
if (isGroupingUsed() && i>0 && (groupingSize != 0) &&
(i % groupingSize == 0)) {
int gStart = result.length();
result.append(grouping);
delegate.formatted(Field.GROUPING_SEPARATOR,
Field.GROUPING_SEPARATOR, gStart,
result.length(), result);
}
}
// Determine whether or not there are any printable fractional
// digits. If we've used up the digits we know there aren't.
boolean fractionPresent = (minFraDigits > 0) ||
(!isInteger && digitIndex < digitList.count);
// If there is no fraction present, and we haven't printed any
// integer digits, then print a zero. Otherwise we won't print
// _any_ digits, and we won't be able to parse this string.
if (!fractionPresent && result.length() == sizeBeforeIntegerPart) {
result.append(zero);
}
delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER,
iFieldStart, result.length(), result);
// Output the decimal separator if we always do so.
int sStart = result.length();
if (decimalSeparatorAlwaysShown || fractionPresent) {
result.append(decimal);
}
if (sStart != result.length()) {
delegate.formatted(Field.DECIMAL_SEPARATOR,
Field.DECIMAL_SEPARATOR,
sStart, result.length(), result);
}
int fFieldStart = result.length();
for (int i=0; i < maxFraDigits; ++i) {
// Here is where we escape from the loop. We escape if we've
// output the maximum fraction digits (specified in the for
// expression above).
// We also stop when we've output the minimum digits and either:
// we have an integer, so there is no fractional stuff to
// display, or we're out of significant digits.
if (i >= minFraDigits &&
(isInteger || digitIndex >= digitList.count)) {
break;
}
// Output leading fractional zeros. These are zeros that come
// after the decimal but before any significant digits. These
// are only output if abs(number being formatted) < 1.0.
if (-1-i > (digitList.decimalAt-1)) {
result.append(zero);
continue;
}
// Output a digit, if we have any precision left, or a
// zero if we don't. We don't want to output noise digits.
if (!isInteger && digitIndex < digitList.count) {
result.append((char)(digitList.digits[digitIndex++] + zeroDelta));
} else {
result.append(zero);
}
}
// Record field information for caller.
delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION,
fFieldStart, result.length(), result);
}
}
/**
* Appends the String {@code string} to {@code result}.
* {@code delegate} is notified of all the
* {@code FieldPosition}s in {@code positions}.
* <p>
* If one of the {@code FieldPosition}s in {@code positions}
* identifies a {@code SIGN} attribute, it is mapped to
* {@code signAttribute}. This is used
* to map the {@code SIGN} attribute to the {@code EXPONENT}
* attribute as necessary.
* <p>
* This is used by {@code subformat} to add the prefix/suffix.
*/
private void append(StringBuffer result, String string,
FieldDelegate delegate,
FieldPosition[] positions,
Format.Field signAttribute) {
int start = result.length();
if (!string.isEmpty()) {
result.append(string);
for (int counter = 0, max = positions.length; counter < max;
counter++) {
FieldPosition fp = positions[counter];
Format.Field attribute = fp.getFieldAttribute();
if (attribute == Field.SIGN) {
attribute = signAttribute;
}
delegate.formatted(attribute, attribute,
start + fp.getBeginIndex(),
start + fp.getEndIndex(), result);
}
}
}
/**
* Parses text from a string to produce a {@code Number}.
* <p>
* The method attempts to parse text starting at the index given by
* {@code pos}.
* If parsing succeeds, then the index of {@code pos} is updated
* to the index after the last character used (parsing does not necessarily
* use all characters up to the end of the string), and the parsed
* number is returned. The updated {@code pos} can be used to
* indicate the starting point for the next call to this method.
* If an error occurs, then the index of {@code pos} is not
* changed, the error index of {@code pos} is set to the index of
* the character where the error occurred, and null is returned.
* <p>
* The subclass returned depends on the value of {@link #isParseBigDecimal}
* as well as on the string being parsed.
* <ul>
* <li>If {@code isParseBigDecimal()} is false (the default),
* most integer values are returned as {@code Long}
* objects, no matter how they are written: {@code "17"} and
* {@code "17.000"} both parse to {@code Long(17)}.
* Values that cannot fit into a {@code Long} are returned as
* {@code Double}s. This includes values with a fractional part,
* infinite values, {@code NaN}, and the value -0.0.
* {@code DecimalFormat} does <em>not</em> decide whether to
* return a {@code Double} or a {@code Long} based on the
* presence of a decimal separator in the source string. Doing so
* would prevent integers that overflow the mantissa of a double,
* such as {@code "-9,223,372,036,854,775,808.00"}, from being
* parsed accurately.
* <p>
* Callers may use the {@code Number} methods
* {@code doubleValue}, {@code longValue}, etc., to obtain
* the type they want.
* <li>If {@code isParseBigDecimal()} is true, values are returned
* as {@code BigDecimal} objects. The values are the ones
* constructed by {@link java.math.BigDecimal#BigDecimal(String)}
* for corresponding strings in locale-independent format. The
* special cases negative and positive infinity and NaN are returned
* as {@code Double} instances holding the values of the
* corresponding {@code Double} constants.
* </ul>
* <p>
* {@code DecimalFormat} parses all Unicode characters that represent
* decimal digits, as defined by {@code Character.digit()}. In
* addition, {@code DecimalFormat} also recognizes as digits the ten
* consecutive characters starting with the localized zero digit defined in
* the {@code DecimalFormatSymbols} object.
*
* @param text the string to be parsed
* @param pos A {@code ParsePosition} object with index and error
* index information as described above.
* @return the parsed value, or {@code null} if the parse fails
* @throws NullPointerException if {@code text} or
* {@code pos} is null.
*/
@Override
public Number parse(String text, ParsePosition pos) {
// special case NaN
if (text.regionMatches(pos.index, symbols.getNaN(), 0, symbols.getNaN().length())) {
pos.index = pos.index + symbols.getNaN().length();
return Double.valueOf(Double.NaN);
}
boolean[] status = new boolean[STATUS_LENGTH];
if (!subparse(text, pos, positivePrefix, negativePrefix, digitList, false, status)) {
return null;
}
// special case INFINITY
if (status[STATUS_INFINITE]) {
if (status[STATUS_POSITIVE] == (multiplier >= 0)) {
return Double.valueOf(Double.POSITIVE_INFINITY);
} else {
return Double.valueOf(Double.NEGATIVE_INFINITY);
}
}
if (multiplier == 0) {
if (digitList.isZero()) {
return Double.valueOf(Double.NaN);
} else if (status[STATUS_POSITIVE]) {
return Double.valueOf(Double.POSITIVE_INFINITY);
} else {
return Double.valueOf(Double.NEGATIVE_INFINITY);
}
}
if (isParseBigDecimal()) {
BigDecimal bigDecimalResult = digitList.getBigDecimal();
if (multiplier != 1) {
try {
bigDecimalResult = bigDecimalResult.divide(getBigDecimalMultiplier());
}
catch (ArithmeticException e) { // non-terminating decimal expansion
bigDecimalResult = bigDecimalResult.divide(getBigDecimalMultiplier(), roundingMode);
}
}
if (!status[STATUS_POSITIVE]) {
bigDecimalResult = bigDecimalResult.negate();
}
return bigDecimalResult;
} else {
boolean gotDouble = true;
boolean gotLongMinimum = false;
double doubleResult = 0.0;
long longResult = 0;
// Finally, have DigitList parse the digits into a value.
if (digitList.fitsIntoLong(status[STATUS_POSITIVE], isParseIntegerOnly())) {
gotDouble = false;
longResult = digitList.getLong();
if (longResult < 0) { // got Long.MIN_VALUE
gotLongMinimum = true;
}
} else {
doubleResult = digitList.getDouble();
}
// Divide by multiplier. We have to be careful here not to do
// unneeded conversions between double and long.
if (multiplier != 1) {
if (gotDouble) {
doubleResult /= multiplier;
} else {
// Avoid converting to double if we can
if (longResult % multiplier == 0) {
longResult /= multiplier;
} else {
doubleResult = ((double)longResult) / multiplier;
gotDouble = true;
}
}
}
if (!status[STATUS_POSITIVE] && !gotLongMinimum) {
doubleResult = -doubleResult;
longResult = -longResult;
}
// At this point, if we divided the result by the multiplier, the
// result may fit into a long. We check for this case and return
// a long if possible.
// We must do this AFTER applying the negative (if appropriate)
// in order to handle the case of LONG_MIN; otherwise, if we do
// this with a positive value -LONG_MIN, the double is > 0, but
// the long is < 0. We also must retain a double in the case of
// -0.0, which will compare as == to a long 0 cast to a double
// (bug 4162852).
if (multiplier != 1 && gotDouble) {
longResult = (long)doubleResult;
gotDouble = ((doubleResult != (double)longResult) ||
(doubleResult == 0.0 && 1/doubleResult < 0.0)) &&
!isParseIntegerOnly();
}
// cast inside of ?: because of binary numeric promotion, JLS 15.25
return gotDouble ? (Number)doubleResult : (Number)longResult;
}
}
/**
* Return a BigInteger multiplier.
*/
private BigInteger getBigIntegerMultiplier() {
if (bigIntegerMultiplier == null) {
bigIntegerMultiplier = BigInteger.valueOf(multiplier);
}
return bigIntegerMultiplier;
}
private transient BigInteger bigIntegerMultiplier;
/**
* Return a BigDecimal multiplier.
*/
private BigDecimal getBigDecimalMultiplier() {
if (bigDecimalMultiplier == null) {
bigDecimalMultiplier = new BigDecimal(multiplier);
}
return bigDecimalMultiplier;
}
private transient BigDecimal bigDecimalMultiplier;
private static final int STATUS_INFINITE = 0;
private static final int STATUS_POSITIVE = 1;
private static final int STATUS_LENGTH = 2;
/**
* Parse the given text into a number. The text is parsed beginning at
* parsePosition, until an unparseable character is seen.
* @param text The string to parse.
* @param parsePosition The position at which to being parsing. Upon
* return, the first unparseable character.
* @param digits The DigitList to set to the parsed value.
* @param isExponent If true, parse an exponent. This means no
* infinite values and integer only.
* @param status Upon return contains boolean status flags indicating
* whether the value was infinite and whether it was positive.
*/
private final boolean subparse(String text, ParsePosition parsePosition,
String positivePrefix, String negativePrefix,
DigitList digits, boolean isExponent,
boolean status[]) {
int position = parsePosition.index;
int oldStart = parsePosition.index;
boolean gotPositive, gotNegative;
// check for positivePrefix; take longest
gotPositive = text.regionMatches(position, positivePrefix, 0,
positivePrefix.length());
gotNegative = text.regionMatches(position, negativePrefix, 0,
negativePrefix.length());
if (gotPositive && gotNegative) {
if (positivePrefix.length() > negativePrefix.length()) {
gotNegative = false;
} else if (positivePrefix.length() < negativePrefix.length()) {
gotPositive = false;
}
}
if (gotPositive) {
position += positivePrefix.length();
} else if (gotNegative) {
position += negativePrefix.length();
} else {
parsePosition.errorIndex = position;
return false;
}
position = subparseNumber(text, position, digits, true, isExponent, status);
if (position == -1) {
parsePosition.index = oldStart;
parsePosition.errorIndex = oldStart;
return false;
}
// Check for suffix
if (!isExponent) {
if (gotPositive) {
gotPositive = text.regionMatches(position,positiveSuffix,0,
positiveSuffix.length());
}
if (gotNegative) {
gotNegative = text.regionMatches(position,negativeSuffix,0,
negativeSuffix.length());
}
// If both match, take longest
if (gotPositive && gotNegative) {
if (positiveSuffix.length() > negativeSuffix.length()) {
gotNegative = false;
} else if (positiveSuffix.length() < negativeSuffix.length()) {
gotPositive = false;
}
}
// Fail if neither or both
if (gotPositive == gotNegative) {
parsePosition.errorIndex = position;
return false;
}
parsePosition.index = position +
(gotPositive ? positiveSuffix.length() : negativeSuffix.length()); // mark success!
} else {
parsePosition.index = position;
}
status[STATUS_POSITIVE] = gotPositive;
if (parsePosition.index == oldStart) {
parsePosition.errorIndex = position;
return false;
}
return true;
}
/**
* Parses a number from the given {@code text}. The text is parsed
* beginning at position, until an unparseable character is seen.
*
* @param text the string to parse
* @param position the position at which parsing begins
* @param digits the DigitList to set to the parsed value
* @param checkExponent whether to check for exponential number
* @param isExponent if the exponential part is encountered
* @param status upon return contains boolean status flags indicating
* whether the value is infinite and whether it is
* positive
* @return returns the position of the first unparseable character or
* -1 in case of no valid number parsed
*/
int subparseNumber(String text, int position,
DigitList digits, boolean checkExponent,
boolean isExponent, boolean status[]) {
// process digits or Inf, find decimal position
status[STATUS_INFINITE] = false;
if (!isExponent && text.regionMatches(position,symbols.getInfinity(),0,
symbols.getInfinity().length())) {
position += symbols.getInfinity().length();
status[STATUS_INFINITE] = true;
} else {
// We now have a string of digits, possibly with grouping symbols,
// and decimal points. We want to process these into a DigitList.
// We don't want to put a bunch of leading zeros into the DigitList
// though, so we keep track of the location of the decimal point,
// put only significant digits into the DigitList, and adjust the
// exponent as needed.
digits.decimalAt = digits.count = 0;
char zero = symbols.getZeroDigit();
char decimal = isCurrencyFormat ?
symbols.getMonetaryDecimalSeparator() :
symbols.getDecimalSeparator();
char grouping = isCurrencyFormat ?
symbols.getMonetaryGroupingSeparator() :
symbols.getGroupingSeparator();
String exponentString = symbols.getExponentSeparator();
boolean sawDecimal = false;
boolean sawExponent = false;
boolean sawDigit = false;
int exponent = 0; // Set to the exponent value, if any
// We have to track digitCount ourselves, because digits.count will
// pin when the maximum allowable digits is reached.
int digitCount = 0;
int backup = -1;
for (; position < text.length(); ++position) {
char ch = text.charAt(position);
/* We recognize all digit ranges, not only the Latin digit range
* '0'..'9'. We do so by using the Character.digit() method,
* which converts a valid Unicode digit to the range 0..9.
*
* The character 'ch' may be a digit. If so, place its value
* from 0 to 9 in 'digit'. First try using the locale digit,
* which may or MAY NOT be a standard Unicode digit range. If
* this fails, try using the standard Unicode digit ranges by
* calling Character.digit(). If this also fails, digit will
* have a value outside the range 0..9.
*/
int digit = ch - zero;
if (digit < 0 || digit > 9) {
digit = Character.digit(ch, 10);
}
if (digit == 0) {
// Cancel out backup setting (see grouping handler below)
backup = -1; // Do this BEFORE continue statement below!!!
sawDigit = true;
// Handle leading zeros
if (digits.count == 0) {
// Ignore leading zeros in integer part of number.
if (!sawDecimal) {
continue;
}
// If we have seen the decimal, but no significant
// digits yet, then we account for leading zeros by
// decrementing the digits.decimalAt into negative
// values.
--digits.decimalAt;
} else {
++digitCount;
digits.append((char)(digit + '0'));
}
} else if (digit > 0 && digit <= 9) { // [sic] digit==0 handled above
sawDigit = true;
++digitCount;
digits.append((char)(digit + '0'));
// Cancel out backup setting (see grouping handler below)
backup = -1;
} else if (!isExponent && ch == decimal) {
// If we're only parsing integers, or if we ALREADY saw the
// decimal, then don't parse this one.
if (isParseIntegerOnly() || sawDecimal) {
break;
}
digits.decimalAt = digitCount; // Not digits.count!
sawDecimal = true;
} else if (!isExponent && ch == grouping && isGroupingUsed()) {
if (sawDecimal) {
break;
}
// Ignore grouping characters, if we are using them, but
// require that they be followed by a digit. Otherwise
// we backup and reprocess them.
backup = position;
} else if (checkExponent && !isExponent && text.regionMatches(position, exponentString, 0, exponentString.length())
&& !sawExponent) {
// Process the exponent by recursively calling this method.
ParsePosition pos = new ParsePosition(position + exponentString.length());
boolean[] stat = new boolean[STATUS_LENGTH];
DigitList exponentDigits = new DigitList();
if (subparse(text, pos, "", symbols.getMinusSignText(), exponentDigits, true, stat) &&
exponentDigits.fitsIntoLong(stat[STATUS_POSITIVE], true)) {
position = pos.index; // Advance past the exponent
exponent = (int)exponentDigits.getLong();
if (!stat[STATUS_POSITIVE]) {
exponent = -exponent;
}
sawExponent = true;
}
break; // Whether we fail or succeed, we exit this loop
} else {
break;
}
}
if (backup != -1) {
position = backup;
}
// If there was no decimal point we have an integer
if (!sawDecimal) {
digits.decimalAt = digitCount; // Not digits.count!
}
// Adjust for exponent, if any
digits.decimalAt += exponent;
// If none of the text string was recognized. For example, parse
// "x" with pattern "#0.00" (return index and error index both 0)
// parse "$" with pattern "$#0.00". (return index 0 and error
// index 1).
if (!sawDigit && digitCount == 0) {
return -1;
}
}
return position;
}
/**
* Returns a copy of the decimal format symbols, which is generally not
* changed by the programmer or user.
* @return a copy of the desired DecimalFormatSymbols
* @see java.text.DecimalFormatSymbols
*/
public DecimalFormatSymbols getDecimalFormatSymbols() {
try {
// don't allow multiple references
return (DecimalFormatSymbols) symbols.clone();
} catch (Exception foo) {
return null; // should never happen
}
}
/**
* Sets the decimal format symbols, which is generally not changed
* by the programmer or user.
* @param newSymbols desired DecimalFormatSymbols
* @see java.text.DecimalFormatSymbols
*/
public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols) {
try {
// don't allow multiple references
symbols = (DecimalFormatSymbols) newSymbols.clone();
expandAffixes();
fastPathCheckNeeded = true;
} catch (Exception foo) {
// should never happen
}
}
/**
* Get the positive prefix.
* <P>Examples: +123, $123, sFr123
*
* @return the positive prefix
*/
public String getPositivePrefix () {
return positivePrefix;
}
/**
* Set the positive prefix.
* <P>Examples: +123, $123, sFr123
*
* @param newValue the new positive prefix
*/
public void setPositivePrefix (String newValue) {
positivePrefix = newValue;
posPrefixPattern = null;
positivePrefixFieldPositions = null;
fastPathCheckNeeded = true;
}
/**
* Returns the FieldPositions of the fields in the prefix used for
* positive numbers. This is not used if the user has explicitly set
* a positive prefix via {@code setPositivePrefix}. This is
* lazily created.
*
* @return FieldPositions in positive prefix
*/
private FieldPosition[] getPositivePrefixFieldPositions() {
if (positivePrefixFieldPositions == null) {
if (posPrefixPattern != null) {
positivePrefixFieldPositions = expandAffix(posPrefixPattern);
} else {
positivePrefixFieldPositions = EmptyFieldPositionArray;
}
}
return positivePrefixFieldPositions;
}
/**
* Get the negative prefix.
* <P>Examples: -123, ($123) (with negative suffix), sFr-123
*
* @return the negative prefix
*/
public String getNegativePrefix () {
return negativePrefix;
}
/**
* Set the negative prefix.
* <P>Examples: -123, ($123) (with negative suffix), sFr-123
*
* @param newValue the new negative prefix
*/
public void setNegativePrefix (String newValue) {
negativePrefix = newValue;
negPrefixPattern = null;
fastPathCheckNeeded = true;
}
/**
* Returns the FieldPositions of the fields in the prefix used for
* negative numbers. This is not used if the user has explicitly set
* a negative prefix via {@code setNegativePrefix}. This is
* lazily created.
*
* @return FieldPositions in positive prefix
*/
private FieldPosition[] getNegativePrefixFieldPositions() {
if (negativePrefixFieldPositions == null) {
if (negPrefixPattern != null) {
negativePrefixFieldPositions = expandAffix(negPrefixPattern);
} else {
negativePrefixFieldPositions = EmptyFieldPositionArray;
}
}
return negativePrefixFieldPositions;
}
/**
* Get the positive suffix.
* <P>Example: 123%
*
* @return the positive suffix
*/
public String getPositiveSuffix () {
return positiveSuffix;
}
/**
* Set the positive suffix.
* <P>Example: 123%
*
* @param newValue the new positive suffix
*/
public void setPositiveSuffix (String newValue) {
positiveSuffix = newValue;
posSuffixPattern = null;
fastPathCheckNeeded = true;
}
/**
* Returns the FieldPositions of the fields in the suffix used for
* positive numbers. This is not used if the user has explicitly set
* a positive suffix via {@code setPositiveSuffix}. This is
* lazily created.
*
* @return FieldPositions in positive prefix
*/
private FieldPosition[] getPositiveSuffixFieldPositions() {
if (positiveSuffixFieldPositions == null) {
if (posSuffixPattern != null) {
positiveSuffixFieldPositions = expandAffix(posSuffixPattern);
} else {
positiveSuffixFieldPositions = EmptyFieldPositionArray;
}
}
return positiveSuffixFieldPositions;
}
/**
* Get the negative suffix.
* <P>Examples: -123%, ($123) (with positive suffixes)
*
* @return the negative suffix
*/
public String getNegativeSuffix () {
return negativeSuffix;
}
/**
* Set the negative suffix.
* <P>Examples: 123%
*
* @param newValue the new negative suffix
*/
public void setNegativeSuffix (String newValue) {
negativeSuffix = newValue;
negSuffixPattern = null;
fastPathCheckNeeded = true;
}
/**
* Returns the FieldPositions of the fields in the suffix used for
* negative numbers. This is not used if the user has explicitly set
* a negative suffix via {@code setNegativeSuffix}. This is
* lazily created.
*
* @return FieldPositions in positive prefix
*/
private FieldPosition[] getNegativeSuffixFieldPositions() {
if (negativeSuffixFieldPositions == null) {
if (negSuffixPattern != null) {
negativeSuffixFieldPositions = expandAffix(negSuffixPattern);
} else {
negativeSuffixFieldPositions = EmptyFieldPositionArray;
}
}
return negativeSuffixFieldPositions;
}
/**
* Gets the multiplier for use in percent, per mille, and similar
* formats.
*
* @return the multiplier
* @see #setMultiplier(int)
*/
public int getMultiplier () {
return multiplier;
}
/**
* Sets the multiplier for use in percent, per mille, and similar
* formats.
* For a percent format, set the multiplier to 100 and the suffixes to
* have '%' (for Arabic, use the Arabic percent sign).
* For a per mille format, set the multiplier to 1000 and the suffixes to
* have '\u2030'.
*
* <P>Example: with multiplier 100, 1.23 is formatted as "123", and
* "123" is parsed into 1.23.
*
* @param newValue the new multiplier
* @see #getMultiplier
*/
public void setMultiplier (int newValue) {
multiplier = newValue;
bigDecimalMultiplier = null;
bigIntegerMultiplier = null;
fastPathCheckNeeded = true;
}
/**
* {@inheritDoc}
*/
@Override
public void setGroupingUsed(boolean newValue) {
super.setGroupingUsed(newValue);
fastPathCheckNeeded = true;
}
/**
* Return the grouping size. Grouping size is the number of digits between
* grouping separators in the integer portion of a number. For example,
* in the number "123,456.78", the grouping size is 3. Grouping size of
* zero designates that grouping is not used, which provides the same
* formatting as if calling {@link #setGroupingUsed(boolean)
* setGroupingUsed(false)}.
*
* @return the grouping size
* @see #setGroupingSize
* @see java.text.NumberFormat#isGroupingUsed
* @see java.text.DecimalFormatSymbols#getGroupingSeparator
*/
public int getGroupingSize () {
return groupingSize;
}
/**
* Set the grouping size. Grouping size is the number of digits between
* grouping separators in the integer portion of a number. For example,
* in the number "123,456.78", the grouping size is 3. Grouping size of
* zero designates that grouping is not used, which provides the same
* formatting as if calling {@link #setGroupingUsed(boolean)
* setGroupingUsed(false)}.
* <p>
* The value passed in is converted to a byte, which may lose information.
* Values that are negative or greater than
* {@link java.lang.Byte#MAX_VALUE Byte.MAX_VALUE}, will throw an
* {@code IllegalArgumentException}.
*
* @param newValue the new grouping size
* @see #getGroupingSize
* @see java.text.NumberFormat#setGroupingUsed
* @see java.text.DecimalFormatSymbols#setGroupingSeparator
* @throws IllegalArgumentException if {@code newValue} is negative or
* greater than {@link java.lang.Byte#MAX_VALUE Byte.MAX_VALUE}
*/
public void setGroupingSize (int newValue) {
if (newValue < 0 || newValue > Byte.MAX_VALUE) {
throw new IllegalArgumentException(
"newValue is out of valid range. value: " + newValue);
}
groupingSize = (byte)newValue;
fastPathCheckNeeded = true;
}
/**
* Allows you to get the behavior of the decimal separator with integers.
* (The decimal separator will always appear with decimals.)
* <P>Example: Decimal ON: 12345 → 12345.; OFF: 12345 → 12345
*
* @return {@code true} if the decimal separator is always shown;
* {@code false} otherwise
*/
public boolean isDecimalSeparatorAlwaysShown() {
return decimalSeparatorAlwaysShown;
}
/**
* Allows you to set the behavior of the decimal separator with integers.
* (The decimal separator will always appear with decimals.)
* <P>Example: Decimal ON: 12345 → 12345.; OFF: 12345 → 12345
*
* @param newValue {@code true} if the decimal separator is always shown;
* {@code false} otherwise
*/
public void setDecimalSeparatorAlwaysShown(boolean newValue) {
decimalSeparatorAlwaysShown = newValue;
fastPathCheckNeeded = true;
}
/**
* Returns whether the {@link #parse(java.lang.String, java.text.ParsePosition)}
* method returns {@code BigDecimal}. The default value is false.
*
* @return {@code true} if the parse method returns BigDecimal;
* {@code false} otherwise
* @see #setParseBigDecimal
* @since 1.5
*/
public boolean isParseBigDecimal() {
return parseBigDecimal;
}
/**
* Sets whether the {@link #parse(java.lang.String, java.text.ParsePosition)}
* method returns {@code BigDecimal}.
*
* @param newValue {@code true} if the parse method returns BigDecimal;
* {@code false} otherwise
* @see #isParseBigDecimal
* @since 1.5
*/
public void setParseBigDecimal(boolean newValue) {
parseBigDecimal = newValue;
}
/**
* Standard override; no change in semantics.
*/
@Override
public Object clone() {
DecimalFormat other = (DecimalFormat) super.clone();
other.symbols = (DecimalFormatSymbols) symbols.clone();
other.digitList = (DigitList) digitList.clone();
// Fast-path is almost stateless algorithm. The only logical state is the
// isFastPath flag. In addition fastPathCheckNeeded is a sentinel flag
// that forces recalculation of all fast-path fields when set to true.
//
// There is thus no need to clone all the fast-path fields.
// We just only need to set fastPathCheckNeeded to true when cloning,
// and init fastPathData to null as if it were a truly new instance.
// Every fast-path field will be recalculated (only once) at next usage of
// fast-path algorithm.
other.fastPathCheckNeeded = true;
other.isFastPath = false;
other.fastPathData = null;
return other;
}
/**
* Overrides equals
*/
@Override
public boolean equals(Object obj)
{
if (obj == null)
return false;
if (!super.equals(obj))
return false; // super does class check
DecimalFormat other = (DecimalFormat) obj;
return ((posPrefixPattern == other.posPrefixPattern &&
positivePrefix.equals(other.positivePrefix))
|| (posPrefixPattern != null &&
posPrefixPattern.equals(other.posPrefixPattern)))
&& ((posSuffixPattern == other.posSuffixPattern &&
positiveSuffix.equals(other.positiveSuffix))
|| (posSuffixPattern != null &&
posSuffixPattern.equals(other.posSuffixPattern)))
&& ((negPrefixPattern == other.negPrefixPattern &&
negativePrefix.equals(other.negativePrefix))
|| (negPrefixPattern != null &&
negPrefixPattern.equals(other.negPrefixPattern)))
&& ((negSuffixPattern == other.negSuffixPattern &&
negativeSuffix.equals(other.negativeSuffix))
|| (negSuffixPattern != null &&
negSuffixPattern.equals(other.negSuffixPattern)))
&& multiplier == other.multiplier
&& groupingSize == other.groupingSize
&& decimalSeparatorAlwaysShown == other.decimalSeparatorAlwaysShown
&& parseBigDecimal == other.parseBigDecimal
&& useExponentialNotation == other.useExponentialNotation
&& (!useExponentialNotation ||
minExponentDigits == other.minExponentDigits)
&& maximumIntegerDigits == other.maximumIntegerDigits
&& minimumIntegerDigits == other.minimumIntegerDigits
&& maximumFractionDigits == other.maximumFractionDigits
&& minimumFractionDigits == other.minimumFractionDigits
&& roundingMode == other.roundingMode
&& symbols.equals(other.symbols);
}
/**
* Overrides hashCode
*/
@Override
public int hashCode() {
return super.hashCode() * 37 + positivePrefix.hashCode();
// just enough fields for a reasonable distribution
}
/**
* Synthesizes a pattern string that represents the current state
* of this Format object.
*
* @return a pattern string
* @see #applyPattern
*/
public String toPattern() {
return toPattern( false );
}
/**
* Synthesizes a localized pattern string that represents the current
* state of this Format object.
*
* @return a localized pattern string
* @see #applyPattern
*/
public String toLocalizedPattern() {
return toPattern( true );
}
/**
* Expand the affix pattern strings into the expanded affix strings. If any
* affix pattern string is null, do not expand it. This method should be
* called any time the symbols or the affix patterns change in order to keep
* the expanded affix strings up to date.
*/
private void expandAffixes() {
// Reuse one StringBuffer for better performance
StringBuffer buffer = new StringBuffer();
if (posPrefixPattern != null) {
positivePrefix = expandAffix(posPrefixPattern, buffer);
positivePrefixFieldPositions = null;
}
if (posSuffixPattern != null) {
positiveSuffix = expandAffix(posSuffixPattern, buffer);
positiveSuffixFieldPositions = null;
}
if (negPrefixPattern != null) {
negativePrefix = expandAffix(negPrefixPattern, buffer);
negativePrefixFieldPositions = null;
}
if (negSuffixPattern != null) {
negativeSuffix = expandAffix(negSuffixPattern, buffer);
negativeSuffixFieldPositions = null;
}
}
/**
* Expand an affix pattern into an affix string. All characters in the
* pattern are literal unless prefixed by QUOTE. The following characters
* after QUOTE are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE,
* PATTERN_MINUS, and CURRENCY_SIGN. If CURRENCY_SIGN is doubled (QUOTE +
* CURRENCY_SIGN + CURRENCY_SIGN), it is interpreted as an ISO 4217
* currency code. Any other character after a QUOTE represents itself.
* QUOTE must be followed by another character; QUOTE may not occur by
* itself at the end of the pattern.
*
* @param pattern the non-null, possibly empty pattern
* @param buffer a scratch StringBuffer; its contents will be lost
* @return the expanded equivalent of pattern
*/
private String expandAffix(String pattern, StringBuffer buffer) {
buffer.setLength(0);
for (int i=0; i<pattern.length(); ) {
char c = pattern.charAt(i++);
if (c == QUOTE) {
c = pattern.charAt(i++);
switch (c) {
case CURRENCY_SIGN:
if (i<pattern.length() &&
pattern.charAt(i) == CURRENCY_SIGN) {
++i;
buffer.append(symbols.getInternationalCurrencySymbol());
} else {
buffer.append(symbols.getCurrencySymbol());
}
continue;
case PATTERN_PERCENT:
buffer.append(symbols.getPercentText());
continue;
case PATTERN_PER_MILLE:
buffer.append(symbols.getPerMillText());
continue;
case PATTERN_MINUS:
buffer.append(symbols.getMinusSignText());
continue;
}
}
buffer.append(c);
}
return buffer.toString();
}
/**
* Expand an affix pattern into an array of FieldPositions describing
* how the pattern would be expanded.
* All characters in the
* pattern are literal unless prefixed by QUOTE. The following characters
* after QUOTE are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE,
* PATTERN_MINUS, and CURRENCY_SIGN. If CURRENCY_SIGN is doubled (QUOTE +
* CURRENCY_SIGN + CURRENCY_SIGN), it is interpreted as an ISO 4217
* currency code. Any other character after a QUOTE represents itself.
* QUOTE must be followed by another character; QUOTE may not occur by
* itself at the end of the pattern.
*
* @param pattern the non-null, possibly empty pattern
* @return FieldPosition array of the resulting fields.
*/
private FieldPosition[] expandAffix(String pattern) {
ArrayList<FieldPosition> positions = null;
int stringIndex = 0;
for (int i=0; i<pattern.length(); ) {
char c = pattern.charAt(i++);
if (c == QUOTE) {
Format.Field fieldID = null;
String string = null;
c = pattern.charAt(i++);
switch (c) {
case CURRENCY_SIGN:
if (i<pattern.length() &&
pattern.charAt(i) == CURRENCY_SIGN) {
++i;
string = symbols.getInternationalCurrencySymbol();
} else {
string = symbols.getCurrencySymbol();
}
fieldID = Field.CURRENCY;
break;
case PATTERN_PERCENT:
string = symbols.getPercentText();
fieldID = Field.PERCENT;
break;
case PATTERN_PER_MILLE:
string = symbols.getPerMillText();
fieldID = Field.PERMILLE;
break;
case PATTERN_MINUS:
string = symbols.getMinusSignText();
fieldID = Field.SIGN;
break;
}
if (fieldID != null && !string.isEmpty()) {
if (positions == null) {
positions = new ArrayList<>(2);
}
FieldPosition fp = new FieldPosition(fieldID);
fp.setBeginIndex(stringIndex);
fp.setEndIndex(stringIndex + string.length());
positions.add(fp);
stringIndex += string.length();
continue;
}
}
stringIndex++;
}
if (positions != null) {
return positions.toArray(EmptyFieldPositionArray);
}
return EmptyFieldPositionArray;
}
/**
* Appends an affix pattern to the given StringBuffer, quoting special
* characters as needed. Uses the internal affix pattern, if that exists,
* or the literal affix, if the internal affix pattern is null. The
* appended string will generate the same affix pattern (or literal affix)
* when passed to toPattern().
*
* @param buffer the affix string is appended to this
* @param affixPattern a pattern such as posPrefixPattern; may be null
* @param expAffix a corresponding expanded affix, such as positivePrefix.
* Ignored unless affixPattern is null. If affixPattern is null, then
* expAffix is appended as a literal affix.
* @param localized true if the appended pattern should contain localized
* pattern characters; otherwise, non-localized pattern chars are appended
*/
private void appendAffix(StringBuffer buffer, String affixPattern,
String expAffix, boolean localized) {
if (affixPattern == null) {
appendAffix(buffer, expAffix, localized);
} else {
int i;
for (int pos=0; pos<affixPattern.length(); pos=i) {
i = affixPattern.indexOf(QUOTE, pos);
if (i < 0) {
appendAffix(buffer, affixPattern.substring(pos), localized);
break;
}
if (i > pos) {
appendAffix(buffer, affixPattern.substring(pos, i), localized);
}
char c = affixPattern.charAt(++i);
++i;
if (c == QUOTE) {
buffer.append(c);
// Fall through and append another QUOTE below
} else if (c == CURRENCY_SIGN &&
i<affixPattern.length() &&
affixPattern.charAt(i) == CURRENCY_SIGN) {
++i;
buffer.append(c);
// Fall through and append another CURRENCY_SIGN below
} else if (localized) {
switch (c) {
case PATTERN_PERCENT:
buffer.append(symbols.getPercentText());
continue;
case PATTERN_PER_MILLE:
buffer.append(symbols.getPerMillText());
continue;
case PATTERN_MINUS:
buffer.append(symbols.getMinusSignText());
continue;
}
}
buffer.append(c);
}
}
}
/**
* Append an affix to the given StringBuffer, using quotes if
* there are special characters. Single quotes themselves must be
* escaped in either case.
*/
private void appendAffix(StringBuffer buffer, String affix, boolean localized) {
boolean needQuote;
if (localized) {
needQuote = affix.indexOf(symbols.getZeroDigit()) >= 0
|| affix.indexOf(symbols.getGroupingSeparator()) >= 0
|| affix.indexOf(symbols.getDecimalSeparator()) >= 0
|| affix.indexOf(symbols.getPercentText()) >= 0
|| affix.indexOf(symbols.getPerMillText()) >= 0
|| affix.indexOf(symbols.getDigit()) >= 0
|| affix.indexOf(symbols.getPatternSeparator()) >= 0
|| affix.indexOf(symbols.getMinusSignText()) >= 0
|| affix.indexOf(CURRENCY_SIGN) >= 0;
} else {
needQuote = affix.indexOf(PATTERN_ZERO_DIGIT) >= 0
|| affix.indexOf(PATTERN_GROUPING_SEPARATOR) >= 0
|| affix.indexOf(PATTERN_DECIMAL_SEPARATOR) >= 0
|| affix.indexOf(PATTERN_PERCENT) >= 0
|| affix.indexOf(PATTERN_PER_MILLE) >= 0
|| affix.indexOf(PATTERN_DIGIT) >= 0
|| affix.indexOf(PATTERN_SEPARATOR) >= 0
|| affix.indexOf(PATTERN_MINUS) >= 0
|| affix.indexOf(CURRENCY_SIGN) >= 0;
}
if (needQuote) buffer.append('\'');
if (affix.indexOf('\'') < 0) buffer.append(affix);
else {
for (int j=0; j<affix.length(); ++j) {
char c = affix.charAt(j);
buffer.append(c);
if (c == '\'') buffer.append(c);
}
}
if (needQuote) buffer.append('\'');
}
/**
* Does the real work of generating a pattern. */
private String toPattern(boolean localized) {
StringBuffer result = new StringBuffer();
for (int j = 1; j >= 0; --j) {
if (j == 1)
appendAffix(result, posPrefixPattern, positivePrefix, localized);
else appendAffix(result, negPrefixPattern, negativePrefix, localized);
int i;
int digitCount = useExponentialNotation
? getMaximumIntegerDigits()
: Math.max(groupingSize, getMinimumIntegerDigits())+1;
for (i = digitCount; i > 0; --i) {
if (i != digitCount && isGroupingUsed() && groupingSize != 0 &&
i % groupingSize == 0) {
result.append(localized ?
(isCurrencyFormat ? symbols.getMonetaryGroupingSeparator() : symbols.getGroupingSeparator()) :
PATTERN_GROUPING_SEPARATOR);
}
result.append(i <= getMinimumIntegerDigits()
? (localized ? symbols.getZeroDigit() : PATTERN_ZERO_DIGIT)
: (localized ? symbols.getDigit() : PATTERN_DIGIT));
}
if (getMaximumFractionDigits() > 0 || decimalSeparatorAlwaysShown)
result.append(localized ?
(isCurrencyFormat ? symbols.getMonetaryDecimalSeparator() : symbols.getDecimalSeparator()) :
PATTERN_DECIMAL_SEPARATOR);
for (i = 0; i < getMaximumFractionDigits(); ++i) {
if (i < getMinimumFractionDigits()) {
result.append(localized ? symbols.getZeroDigit() :
PATTERN_ZERO_DIGIT);
} else {
result.append(localized ? symbols.getDigit() :
PATTERN_DIGIT);
}
}
if (useExponentialNotation)
{
result.append(localized ? symbols.getExponentSeparator() :
PATTERN_EXPONENT);
for (i=0; i<minExponentDigits; ++i)
result.append(localized ? symbols.getZeroDigit() :
PATTERN_ZERO_DIGIT);
}
if (j == 1) {
appendAffix(result, posSuffixPattern, positiveSuffix, localized);
if ((negSuffixPattern == posSuffixPattern && // n == p == null
negativeSuffix.equals(positiveSuffix))
|| (negSuffixPattern != null &&
negSuffixPattern.equals(posSuffixPattern))) {
if ((negPrefixPattern != null && posPrefixPattern != null &&
negPrefixPattern.equals("'-" + posPrefixPattern)) ||
(negPrefixPattern == posPrefixPattern && // n == p == null
negativePrefix.equals(symbols.getMinusSignText() + positivePrefix)))
break;
}
result.append(localized ? symbols.getPatternSeparator() :
PATTERN_SEPARATOR);
} else appendAffix(result, negSuffixPattern, negativeSuffix, localized);
}
return result.toString();
}
/**
* Apply the given pattern to this Format object. A pattern is a
* short-hand specification for the various formatting properties.
* These properties can also be changed individually through the
* various setter methods.
* <p>
* There is no limit to integer digits set
* by this routine, since that is the typical end-user desire;
* use setMaximumInteger if you want to set a real value.
* For negative numbers, use a second pattern, separated by a semicolon
* <P>Example {@code "#,#00.0#"} → 1,234.56
* <P>This means a minimum of 2 integer digits, 1 fraction digit, and
* a maximum of 2 fraction digits.
* <p>Example: {@code "#,#00.0#;(#,#00.0#)"} for negatives in
* parentheses.
* <p>In negative patterns, the minimum and maximum counts are ignored;
* these are presumed to be set in the positive pattern.
*
* @param pattern a new pattern
* @throws NullPointerException if {@code pattern} is null
* @throws IllegalArgumentException if the given pattern is invalid.
*/
public void applyPattern(String pattern) {
applyPattern(pattern, false);
}
/**
* Apply the given pattern to this Format object. The pattern
* is assumed to be in a localized notation. A pattern is a
* short-hand specification for the various formatting properties.
* These properties can also be changed individually through the
* various setter methods.
* <p>
* There is no limit to integer digits set
* by this routine, since that is the typical end-user desire;
* use setMaximumInteger if you want to set a real value.
* For negative numbers, use a second pattern, separated by a semicolon
* <P>Example {@code "#,#00.0#"} → 1,234.56
* <P>This means a minimum of 2 integer digits, 1 fraction digit, and
* a maximum of 2 fraction digits.
* <p>Example: {@code "#,#00.0#;(#,#00.0#)"} for negatives in
* parentheses.
* <p>In negative patterns, the minimum and maximum counts are ignored;
* these are presumed to be set in the positive pattern.
*
* @param pattern a new pattern
* @throws NullPointerException if {@code pattern} is null
* @throws IllegalArgumentException if the given pattern is invalid.
*/
public void applyLocalizedPattern(String pattern) {
applyPattern(pattern, true);
}
/**
* Does the real work of applying a pattern.
*/
private void applyPattern(String pattern, boolean localized) {
char zeroDigit = PATTERN_ZERO_DIGIT;
char groupingSeparator = PATTERN_GROUPING_SEPARATOR;
char decimalSeparator = PATTERN_DECIMAL_SEPARATOR;
char percent = PATTERN_PERCENT;
char perMill = PATTERN_PER_MILLE;
char digit = PATTERN_DIGIT;
char separator = PATTERN_SEPARATOR;
String exponent = PATTERN_EXPONENT;
char minus = PATTERN_MINUS;
if (localized) {
zeroDigit = symbols.getZeroDigit();
groupingSeparator = symbols.getGroupingSeparator();
decimalSeparator = symbols.getDecimalSeparator();
percent = symbols.getPercent();
perMill = symbols.getPerMill();
digit = symbols.getDigit();
separator = symbols.getPatternSeparator();
exponent = symbols.getExponentSeparator();
minus = symbols.getMinusSign();
}
boolean gotNegative = false;
decimalSeparatorAlwaysShown = false;
isCurrencyFormat = false;
useExponentialNotation = false;
int start = 0;
for (int j = 1; j >= 0 && start < pattern.length(); --j) {
boolean inQuote = false;
StringBuffer prefix = new StringBuffer();
StringBuffer suffix = new StringBuffer();
int decimalPos = -1;
int multiplier = 1;
int digitLeftCount = 0, zeroDigitCount = 0, digitRightCount = 0;
byte groupingCount = -1;
// The phase ranges from 0 to 2. Phase 0 is the prefix. Phase 1 is
// the section of the pattern with digits, decimal separator,
// grouping characters. Phase 2 is the suffix. In phases 0 and 2,
// percent, per mille, and currency symbols are recognized and
// translated. The separation of the characters into phases is
// strictly enforced; if phase 1 characters are to appear in the
// suffix, for example, they must be quoted.
int phase = 0;
// The affix is either the prefix or the suffix.
StringBuffer affix = prefix;
for (int pos = start; pos < pattern.length(); ++pos) {
char ch = pattern.charAt(pos);
switch (phase) {
case 0:
case 2:
// Process the prefix / suffix characters
if (inQuote) {
// A quote within quotes indicates either the closing
// quote or two quotes, which is a quote literal. That
// is, we have the second quote in 'do' or 'don''t'.
if (ch == QUOTE) {
if ((pos+1) < pattern.length() &&
pattern.charAt(pos+1) == QUOTE) {
++pos;
affix.append("''"); // 'don''t'
} else {
inQuote = false; // 'do'
}
continue;
}
} else {
// Process unquoted characters seen in prefix or suffix
// phase.
if (ch == digit ||
ch == zeroDigit ||
ch == groupingSeparator ||
ch == decimalSeparator) {
phase = 1;
--pos; // Reprocess this character
continue;
} else if (ch == CURRENCY_SIGN) {
// Use lookahead to determine if the currency sign
// is doubled or not.
boolean doubled = (pos + 1) < pattern.length() &&
pattern.charAt(pos + 1) == CURRENCY_SIGN;
if (doubled) { // Skip over the doubled character
++pos;
}
isCurrencyFormat = true;
affix.append(doubled ? "'\u00A4\u00A4" : "'\u00A4");
continue;
} else if (ch == QUOTE) {
// A quote outside quotes indicates either the
// opening quote or two quotes, which is a quote
// literal. That is, we have the first quote in 'do'
// or o''clock.
if (ch == QUOTE) {
if ((pos+1) < pattern.length() &&
pattern.charAt(pos+1) == QUOTE) {
++pos;
affix.append("''"); // o''clock
} else {
inQuote = true; // 'do'
}
continue;
}
} else if (ch == separator) {
// Don't allow separators before we see digit
// characters of phase 1, and don't allow separators
// in the second pattern (j == 0).
if (phase == 0 || j == 0) {
throw new IllegalArgumentException("Unquoted special character '" +
ch + "' in pattern \"" + pattern + '"');
}
start = pos + 1;
pos = pattern.length();
continue;
}
// Next handle characters which are appended directly.
else if (ch == percent) {
if (multiplier != 1) {
throw new IllegalArgumentException("Too many percent/per mille characters in pattern \"" +
pattern + '"');
}
multiplier = 100;
affix.append("'%");
continue;
} else if (ch == perMill) {
if (multiplier != 1) {
throw new IllegalArgumentException("Too many percent/per mille characters in pattern \"" +
pattern + '"');
}
multiplier = 1000;
affix.append("'\u2030");
continue;
} else if (ch == minus) {
affix.append("'-");
continue;
}
}
// Note that if we are within quotes, or if this is an
// unquoted, non-special character, then we usually fall
// through to here.
affix.append(ch);
break;
case 1:
// The negative subpattern (j = 0) serves only to specify the
// negative prefix and suffix, so all the phase 1 characters
// e.g. digits, zeroDigit, groupingSeparator,
// decimalSeparator, exponent are ignored
if (j == 0) {
while (pos < pattern.length()) {
char negPatternChar = pattern.charAt(pos);
if (negPatternChar == digit
|| negPatternChar == zeroDigit
|| negPatternChar == groupingSeparator
|| negPatternChar == decimalSeparator) {
++pos;
} else if (pattern.regionMatches(pos, exponent,
0, exponent.length())) {
pos = pos + exponent.length();
} else {
// Not a phase 1 character, consider it as
// suffix and parse it in phase 2
--pos; //process it again in outer loop
phase = 2;
affix = suffix;
break;
}
}
continue;
}
// Process the digits, decimal, and grouping characters. We
// record five pieces of information. We expect the digits
// to occur in the pattern ####0000.####, and we record the
// number of left digits, zero (central) digits, and right
// digits. The position of the last grouping character is
// recorded (should be somewhere within the first two blocks
// of characters), as is the position of the decimal point,
// if any (should be in the zero digits). If there is no
// decimal point, then there should be no right digits.
if (ch == digit) {
if (zeroDigitCount > 0) {
++digitRightCount;
} else {
++digitLeftCount;
}
if (groupingCount >= 0 && decimalPos < 0) {
++groupingCount;
}
} else if (ch == zeroDigit) {
if (digitRightCount > 0) {
throw new IllegalArgumentException("Unexpected '0' in pattern \"" +
pattern + '"');
}
++zeroDigitCount;
if (groupingCount >= 0 && decimalPos < 0) {
++groupingCount;
}
} else if (ch == groupingSeparator) {
groupingCount = 0;
} else if (ch == decimalSeparator) {
if (decimalPos >= 0) {
throw new IllegalArgumentException("Multiple decimal separators in pattern \"" +
pattern + '"');
}
decimalPos = digitLeftCount + zeroDigitCount + digitRightCount;
} else if (pattern.regionMatches(pos, exponent, 0, exponent.length())){
if (useExponentialNotation) {
throw new IllegalArgumentException("Multiple exponential " +
"symbols in pattern \"" + pattern + '"');
}
useExponentialNotation = true;
minExponentDigits = 0;
// Use lookahead to parse out the exponential part
// of the pattern, then jump into phase 2.
pos = pos+exponent.length();
while (pos < pattern.length() &&
pattern.charAt(pos) == zeroDigit) {
++minExponentDigits;
++pos;
}
if ((digitLeftCount + zeroDigitCount) < 1 ||
minExponentDigits < 1) {
throw new IllegalArgumentException("Malformed exponential " +
"pattern \"" + pattern + '"');
}
// Transition to phase 2
phase = 2;
affix = suffix;
--pos;
continue;
} else {
phase = 2;
affix = suffix;
--pos;
continue;
}
break;
}
}
// Handle patterns with no '0' pattern character. These patterns
// are legal, but must be interpreted. "##.###" -> "#0.###".
// ".###" -> ".0##".
/* We allow patterns of the form "####" to produce a zeroDigitCount
* of zero (got that?); although this seems like it might make it
* possible for format() to produce empty strings, format() checks
* for this condition and outputs a zero digit in this situation.
* Having a zeroDigitCount of zero yields a minimum integer digits
* of zero, which allows proper round-trip patterns. That is, we
* don't want "#" to become "#0" when toPattern() is called (even
* though that's what it really is, semantically).
*/
if (zeroDigitCount == 0 && digitLeftCount > 0 && decimalPos >= 0) {
// Handle "###.###" and "###." and ".###"
int n = decimalPos;
if (n == 0) { // Handle ".###"
++n;
}
digitRightCount = digitLeftCount - n;
digitLeftCount = n - 1;
zeroDigitCount = 1;
}
// Do syntax checking on the digits.
if ((decimalPos < 0 && digitRightCount > 0) ||
(decimalPos >= 0 && (decimalPos < digitLeftCount ||
decimalPos > (digitLeftCount + zeroDigitCount))) ||
groupingCount == 0 || inQuote) {
throw new IllegalArgumentException("Malformed pattern \"" +
pattern + '"');
}
if (j == 1) {
posPrefixPattern = prefix.toString();
posSuffixPattern = suffix.toString();
negPrefixPattern = posPrefixPattern; // assume these for now
negSuffixPattern = posSuffixPattern;
int digitTotalCount = digitLeftCount + zeroDigitCount + digitRightCount;
/* The effectiveDecimalPos is the position the decimal is at or
* would be at if there is no decimal. Note that if decimalPos<0,
* then digitTotalCount == digitLeftCount + zeroDigitCount.
*/
int effectiveDecimalPos = decimalPos >= 0 ?
decimalPos : digitTotalCount;
setMinimumIntegerDigits(effectiveDecimalPos - digitLeftCount);
setMaximumIntegerDigits(useExponentialNotation ?
digitLeftCount + getMinimumIntegerDigits() :
MAXIMUM_INTEGER_DIGITS);
setMaximumFractionDigits(decimalPos >= 0 ?
(digitTotalCount - decimalPos) : 0);
setMinimumFractionDigits(decimalPos >= 0 ?
(digitLeftCount + zeroDigitCount - decimalPos) : 0);
setGroupingUsed(groupingCount > 0);
this.groupingSize = (groupingCount > 0) ? groupingCount : 0;
this.multiplier = multiplier;
setDecimalSeparatorAlwaysShown(decimalPos == 0 ||
decimalPos == digitTotalCount);
} else {
negPrefixPattern = prefix.toString();
negSuffixPattern = suffix.toString();
gotNegative = true;
}
}
if (pattern.isEmpty()) {
posPrefixPattern = posSuffixPattern = "";
setMinimumIntegerDigits(0);
setMaximumIntegerDigits(MAXIMUM_INTEGER_DIGITS);
setMinimumFractionDigits(0);
setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);
}
// If there was no negative pattern, or if the negative pattern is
// identical to the positive pattern, then prepend the minus sign to
// the positive pattern to form the negative pattern.
if (!gotNegative ||
(negPrefixPattern.equals(posPrefixPattern)
&& negSuffixPattern.equals(posSuffixPattern))) {
negSuffixPattern = posSuffixPattern;
negPrefixPattern = "'-" + posPrefixPattern;
}
expandAffixes();
}
/**
* Sets the maximum number of digits allowed in the integer portion of a
* number.
* For formatting numbers other than {@code BigInteger} and
* {@code BigDecimal} objects, the lower of {@code newValue} and
* 309 is used. Negative input values are replaced with 0.
* @see NumberFormat#setMaximumIntegerDigits
*/
@Override
public void setMaximumIntegerDigits(int newValue) {
maximumIntegerDigits = Math.min(Math.max(0, newValue), MAXIMUM_INTEGER_DIGITS);
super.setMaximumIntegerDigits((maximumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
DOUBLE_INTEGER_DIGITS : maximumIntegerDigits);
if (minimumIntegerDigits > maximumIntegerDigits) {
minimumIntegerDigits = maximumIntegerDigits;
super.setMinimumIntegerDigits((minimumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
DOUBLE_INTEGER_DIGITS : minimumIntegerDigits);
}
fastPathCheckNeeded = true;
}
/**
* Sets the minimum number of digits allowed in the integer portion of a
* number.
* For formatting numbers other than {@code BigInteger} and
* {@code BigDecimal} objects, the lower of {@code newValue} and
* 309 is used. Negative input values are replaced with 0.
* @see NumberFormat#setMinimumIntegerDigits
*/
@Override
public void setMinimumIntegerDigits(int newValue) {
minimumIntegerDigits = Math.min(Math.max(0, newValue), MAXIMUM_INTEGER_DIGITS);
super.setMinimumIntegerDigits((minimumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
DOUBLE_INTEGER_DIGITS : minimumIntegerDigits);
if (minimumIntegerDigits > maximumIntegerDigits) {
maximumIntegerDigits = minimumIntegerDigits;
super.setMaximumIntegerDigits((maximumIntegerDigits > DOUBLE_INTEGER_DIGITS) ?
DOUBLE_INTEGER_DIGITS : maximumIntegerDigits);
}
fastPathCheckNeeded = true;
}
/**
* Sets the maximum number of digits allowed in the fraction portion of a
* number.
* For formatting numbers other than {@code BigInteger} and
* {@code BigDecimal} objects, the lower of {@code newValue} and
* 340 is used. Negative input values are replaced with 0.
* @see NumberFormat#setMaximumFractionDigits
*/
@Override
public void setMaximumFractionDigits(int newValue) {
maximumFractionDigits = Math.min(Math.max(0, newValue), MAXIMUM_FRACTION_DIGITS);
super.setMaximumFractionDigits((maximumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
DOUBLE_FRACTION_DIGITS : maximumFractionDigits);
if (minimumFractionDigits > maximumFractionDigits) {
minimumFractionDigits = maximumFractionDigits;
super.setMinimumFractionDigits((minimumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
DOUBLE_FRACTION_DIGITS : minimumFractionDigits);
}
fastPathCheckNeeded = true;
}
/**
* Sets the minimum number of digits allowed in the fraction portion of a
* number.
* For formatting numbers other than {@code BigInteger} and
* {@code BigDecimal} objects, the lower of {@code newValue} and
* 340 is used. Negative input values are replaced with 0.
* @see NumberFormat#setMinimumFractionDigits
*/
@Override
public void setMinimumFractionDigits(int newValue) {
minimumFractionDigits = Math.min(Math.max(0, newValue), MAXIMUM_FRACTION_DIGITS);
super.setMinimumFractionDigits((minimumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
DOUBLE_FRACTION_DIGITS : minimumFractionDigits);
if (minimumFractionDigits > maximumFractionDigits) {
maximumFractionDigits = minimumFractionDigits;
super.setMaximumFractionDigits((maximumFractionDigits > DOUBLE_FRACTION_DIGITS) ?
DOUBLE_FRACTION_DIGITS : maximumFractionDigits);
}
fastPathCheckNeeded = true;
}
/**
* Gets the maximum number of digits allowed in the integer portion of a
* number.
* For formatting numbers other than {@code BigInteger} and
* {@code BigDecimal} objects, the lower of the return value and
* 309 is used.
* @see #setMaximumIntegerDigits
*/
@Override
public int getMaximumIntegerDigits() {
return maximumIntegerDigits;
}
/**
* Gets the minimum number of digits allowed in the integer portion of a
* number.
* For formatting numbers other than {@code BigInteger} and
* {@code BigDecimal} objects, the lower of the return value and
* 309 is used.
* @see #setMinimumIntegerDigits
*/
@Override
public int getMinimumIntegerDigits() {
return minimumIntegerDigits;
}
/**
* Gets the maximum number of digits allowed in the fraction portion of a
* number.
* For formatting numbers other than {@code BigInteger} and
* {@code BigDecimal} objects, the lower of the return value and
* 340 is used.
* @see #setMaximumFractionDigits
*/
@Override
public int getMaximumFractionDigits() {
return maximumFractionDigits;
}
/**
* Gets the minimum number of digits allowed in the fraction portion of a
* number.
* For formatting numbers other than {@code BigInteger} and
* {@code BigDecimal} objects, the lower of the return value and
* 340 is used.
* @see #setMinimumFractionDigits
*/
@Override
public int getMinimumFractionDigits() {
return minimumFractionDigits;
}
/**
* Gets the currency used by this decimal format when formatting
* currency values.
* The currency is obtained by calling
* {@link DecimalFormatSymbols#getCurrency DecimalFormatSymbols.getCurrency}
* on this number format's symbols.
*
* @return the currency used by this decimal format, or {@code null}
* @since 1.4
*/
@Override
public Currency getCurrency() {
return symbols.getCurrency();
}
/**
* Sets the currency used by this number format when formatting
* currency values. This does not update the minimum or maximum
* number of fraction digits used by the number format.
* The currency is set by calling
* {@link DecimalFormatSymbols#setCurrency DecimalFormatSymbols.setCurrency}
* on this number format's symbols.
*
* @param currency the new currency to be used by this decimal format
* @throws NullPointerException if {@code currency} is null
* @since 1.4
*/
@Override
public void setCurrency(Currency currency) {
if (currency != symbols.getCurrency()) {
symbols.setCurrency(currency);
if (isCurrencyFormat) {
expandAffixes();
}
}
fastPathCheckNeeded = true;
}
/**
* Gets the {@link java.math.RoundingMode} used in this DecimalFormat.
*
* @return The {@code RoundingMode} used for this DecimalFormat.
* @see #setRoundingMode(RoundingMode)
* @since 1.6
*/
@Override
public RoundingMode getRoundingMode() {
return roundingMode;
}
/**
* Sets the {@link java.math.RoundingMode} used in this DecimalFormat.
*
* @param roundingMode The {@code RoundingMode} to be used
* @see #getRoundingMode()
* @throws NullPointerException if {@code roundingMode} is null.
* @since 1.6
*/
@Override
public void setRoundingMode(RoundingMode roundingMode) {
if (roundingMode == null) {
throw new NullPointerException();
}
this.roundingMode = roundingMode;
digitList.setRoundingMode(roundingMode);
fastPathCheckNeeded = true;
}
/**
* Reads the default serializable fields from the stream and performs
* validations and adjustments for older serialized versions. The
* validations and adjustments are:
* <ol>
* <li>
* Verify that the superclass's digit count fields correctly reflect
* the limits imposed on formatting numbers other than
* {@code BigInteger} and {@code BigDecimal} objects. These
* limits are stored in the superclass for serialization compatibility
* with older versions, while the limits for {@code BigInteger} and
* {@code BigDecimal} objects are kept in this class.
* If, in the superclass, the minimum or maximum integer digit count is
* larger than {@code DOUBLE_INTEGER_DIGITS} or if the minimum or
* maximum fraction digit count is larger than
* {@code DOUBLE_FRACTION_DIGITS}, then the stream data is invalid
* and this method throws an {@code InvalidObjectException}.
* <li>
* If {@code serialVersionOnStream} is less than 4, initialize
* {@code roundingMode} to {@link java.math.RoundingMode#HALF_EVEN
* RoundingMode.HALF_EVEN}. This field is new with version 4.
* <li>
* If {@code serialVersionOnStream} is less than 3, then call
* the setters for the minimum and maximum integer and fraction digits with
* the values of the corresponding superclass getters to initialize the
* fields in this class. The fields in this class are new with version 3.
* <li>
* If {@code serialVersionOnStream} is less than 1, indicating that
* the stream was written by JDK 1.1, initialize
* {@code useExponentialNotation}
* to false, since it was not present in JDK 1.1.
* <li>
* Set {@code serialVersionOnStream} to the maximum allowed value so
* that default serialization will work properly if this object is streamed
* out again.
* </ol>
*
* <p>Stream versions older than 2 will not have the affix pattern variables
* {@code posPrefixPattern} etc. As a result, they will be initialized
* to {@code null}, which means the affix strings will be taken as
* literal values. This is exactly what we want, since that corresponds to
* the pre-version-2 behavior.
*/
@java.io.Serial
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException
{
stream.defaultReadObject();
digitList = new DigitList();
// We force complete fast-path reinitialization when the instance is
// deserialized. See clone() comment on fastPathCheckNeeded.
fastPathCheckNeeded = true;
isFastPath = false;
fastPathData = null;
if (serialVersionOnStream < 4) {
setRoundingMode(RoundingMode.HALF_EVEN);
} else {
setRoundingMode(getRoundingMode());
}
// We only need to check the maximum counts because NumberFormat
// .readObject has already ensured that the maximum is greater than the
// minimum count.
if (super.getMaximumIntegerDigits() > DOUBLE_INTEGER_DIGITS ||
super.getMaximumFractionDigits() > DOUBLE_FRACTION_DIGITS) {
throw new InvalidObjectException("Digit count out of range");
}
if (serialVersionOnStream < 3) {
setMaximumIntegerDigits(super.getMaximumIntegerDigits());
setMinimumIntegerDigits(super.getMinimumIntegerDigits());
setMaximumFractionDigits(super.getMaximumFractionDigits());
setMinimumFractionDigits(super.getMinimumFractionDigits());
}
if (serialVersionOnStream < 1) {
// Didn't have exponential fields
useExponentialNotation = false;
}
// Restore the invariant value if groupingSize is invalid.
if (groupingSize < 0) {
groupingSize = 3;
}
serialVersionOnStream = currentSerialVersion;
}
//----------------------------------------------------------------------
// INSTANCE VARIABLES
//----------------------------------------------------------------------
private transient DigitList digitList = new DigitList();
/**
* The symbol used as a prefix when formatting positive numbers, e.g. "+".
*
* @serial
* @see #getPositivePrefix
*/
private String positivePrefix = "";
/**
* The symbol used as a suffix when formatting positive numbers.
* This is often an empty string.
*
* @serial
* @see #getPositiveSuffix
*/
private String positiveSuffix = "";
/**
* The symbol used as a prefix when formatting negative numbers, e.g. "-".
*
* @serial
* @see #getNegativePrefix
*/
private String negativePrefix = "-";
/**
* The symbol used as a suffix when formatting negative numbers.
* This is often an empty string.
*
* @serial
* @see #getNegativeSuffix
*/
private String negativeSuffix = "";
/**
* The prefix pattern for non-negative numbers. This variable corresponds
* to {@code positivePrefix}.
*
* <p>This pattern is expanded by the method {@code expandAffix()} to
* {@code positivePrefix} to update the latter to reflect changes in
* {@code symbols}. If this variable is {@code null} then
* {@code positivePrefix} is taken as a literal value that does not
* change when {@code symbols} changes. This variable is always
* {@code null} for {@code DecimalFormat} objects older than
* stream version 2 restored from stream.
*
* @serial
* @since 1.3
*/
private String posPrefixPattern;
/**
* The suffix pattern for non-negative numbers. This variable corresponds
* to {@code positiveSuffix}. This variable is analogous to
* {@code posPrefixPattern}; see that variable for further
* documentation.
*
* @serial
* @since 1.3
*/
private String posSuffixPattern;
/**
* The prefix pattern for negative numbers. This variable corresponds
* to {@code negativePrefix}. This variable is analogous to
* {@code posPrefixPattern}; see that variable for further
* documentation.
*
* @serial
* @since 1.3
*/
private String negPrefixPattern;
/**
* The suffix pattern for negative numbers. This variable corresponds
* to {@code negativeSuffix}. This variable is analogous to
* {@code posPrefixPattern}; see that variable for further
* documentation.
*
* @serial
* @since 1.3
*/
private String negSuffixPattern;
/**
* The multiplier for use in percent, per mille, etc.
*
* @serial
* @see #getMultiplier
*/
private int multiplier = 1;
/**
* The number of digits between grouping separators in the integer
* portion of a number. Must be non-negative and less than or equal to
* {@link java.lang.Byte#MAX_VALUE Byte.MAX_VALUE} if
* {@code NumberFormat.groupingUsed} is true.
*
* @serial
* @see #getGroupingSize
* @see java.text.NumberFormat#isGroupingUsed
*/
private byte groupingSize = 3; // invariant, 0 - 127, if groupingUsed
/**
* If true, forces the decimal separator to always appear in a formatted
* number, even if the fractional part of the number is zero.
*
* @serial
* @see #isDecimalSeparatorAlwaysShown
*/
private boolean decimalSeparatorAlwaysShown = false;
/**
* If true, parse returns BigDecimal wherever possible.
*
* @serial
* @see #isParseBigDecimal
* @since 1.5
*/
private boolean parseBigDecimal = false;
/**
* True if this object represents a currency format. This determines
* whether the monetary decimal/grouping separators are used instead of the normal ones.
*/
private transient boolean isCurrencyFormat = false;
/**
* The {@code DecimalFormatSymbols} object used by this format.
* It contains the symbols used to format numbers, e.g. the grouping separator,
* decimal separator, and so on.
*
* @serial
* @see #setDecimalFormatSymbols
* @see java.text.DecimalFormatSymbols
*/
private DecimalFormatSymbols symbols = null; // LIU new DecimalFormatSymbols();
/**
* True to force the use of exponential (i.e. scientific) notation when formatting
* numbers.
*
* @serial
* @since 1.2
*/
private boolean useExponentialNotation; // Newly persistent in the Java 2 platform v.1.2
/**
* FieldPositions describing the positive prefix String. This is
* lazily created. Use {@code getPositivePrefixFieldPositions}
* when needed.
*/
private transient FieldPosition[] positivePrefixFieldPositions;
/**
* FieldPositions describing the positive suffix String. This is
* lazily created. Use {@code getPositiveSuffixFieldPositions}
* when needed.
*/
private transient FieldPosition[] positiveSuffixFieldPositions;
/**
* FieldPositions describing the negative prefix String. This is
* lazily created. Use {@code getNegativePrefixFieldPositions}
* when needed.
*/
private transient FieldPosition[] negativePrefixFieldPositions;
/**
* FieldPositions describing the negative suffix String. This is
* lazily created. Use {@code getNegativeSuffixFieldPositions}
* when needed.
*/
private transient FieldPosition[] negativeSuffixFieldPositions;
/**
* The minimum number of digits used to display the exponent when a number is
* formatted in exponential notation. This field is ignored if
* {@code useExponentialNotation} is not true.
*
* @serial
* @since 1.2
*/
private byte minExponentDigits; // Newly persistent in the Java 2 platform v.1.2
/**
* The maximum number of digits allowed in the integer portion of a
* {@code BigInteger} or {@code BigDecimal} number.
* {@code maximumIntegerDigits} must be greater than or equal to
* {@code minimumIntegerDigits}.
*
* @serial
* @see #getMaximumIntegerDigits
* @since 1.5
*/
private int maximumIntegerDigits = super.getMaximumIntegerDigits();
/**
* The minimum number of digits allowed in the integer portion of a
* {@code BigInteger} or {@code BigDecimal} number.
* {@code minimumIntegerDigits} must be less than or equal to
* {@code maximumIntegerDigits}.
*
* @serial
* @see #getMinimumIntegerDigits
* @since 1.5
*/
private int minimumIntegerDigits = super.getMinimumIntegerDigits();
/**
* The maximum number of digits allowed in the fractional portion of a
* {@code BigInteger} or {@code BigDecimal} number.
* {@code maximumFractionDigits} must be greater than or equal to
* {@code minimumFractionDigits}.
*
* @serial
* @see #getMaximumFractionDigits
* @since 1.5
*/
private int maximumFractionDigits = super.getMaximumFractionDigits();
/**
* The minimum number of digits allowed in the fractional portion of a
* {@code BigInteger} or {@code BigDecimal} number.
* {@code minimumFractionDigits} must be less than or equal to
* {@code maximumFractionDigits}.
*
* @serial
* @see #getMinimumFractionDigits
* @since 1.5
*/
private int minimumFractionDigits = super.getMinimumFractionDigits();
/**
* The {@link java.math.RoundingMode} used in this DecimalFormat.
*
* @serial
* @since 1.6
*/
private RoundingMode roundingMode = RoundingMode.HALF_EVEN;
// ------ DecimalFormat fields for fast-path for double algorithm ------
/**
* Helper inner utility class for storing the data used in the fast-path
* algorithm. Almost all fields related to fast-path are encapsulated in
* this class.
*
* Any {@code DecimalFormat} instance has a {@code fastPathData}
* reference field that is null unless both the properties of the instance
* are such that the instance is in the "fast-path" state, and a format call
* has been done at least once while in this state.
*
* Almost all fields are related to the "fast-path" state only and don't
* change until one of the instance properties is changed.
*
* {@code firstUsedIndex} and {@code lastFreeIndex} are the only
* two fields that are used and modified while inside a call to
* {@code fastDoubleFormat}.
*
*/
private static class FastPathData {
// --- Temporary fields used in fast-path, shared by several methods.
/** The first unused index at the end of the formatted result. */
int lastFreeIndex;
/** The first used index at the beginning of the formatted result */
int firstUsedIndex;
// --- State fields related to fast-path status. Changes due to a
// property change only. Set by checkAndSetFastPathStatus() only.
/** Difference between locale zero and default zero representation. */
int zeroDelta;
/** Locale char for grouping separator. */
char groupingChar;
/** Fixed index position of last integral digit of formatted result */
int integralLastIndex;
/** Fixed index position of first fractional digit of formatted result */
int fractionalFirstIndex;
/** Fractional constants depending on decimal|currency state */
double fractionalScaleFactor;
int fractionalMaxIntBound;
/** The char array buffer that will contain the formatted result */
char[] fastPathContainer;
/** Suffixes recorded as char array for efficiency. */
char[] charsPositivePrefix;
char[] charsNegativePrefix;
char[] charsPositiveSuffix;
char[] charsNegativeSuffix;
boolean positiveAffixesRequired = true;
boolean negativeAffixesRequired = true;
}
/** The format fast-path status of the instance. Logical state. */
private transient boolean isFastPath = false;
/** Flag stating need of check and reinit fast-path status on next format call. */
private transient boolean fastPathCheckNeeded = true;
/** DecimalFormat reference to its FastPathData */
private transient FastPathData fastPathData;
//----------------------------------------------------------------------
static final int currentSerialVersion = 4;
/**
* The internal serial version which says which version was written.
* Possible values are:
* <ul>
* <li><b>0</b> (default): versions before the Java 2 platform v1.2
* <li><b>1</b>: version for 1.2, which includes the two new fields
* {@code useExponentialNotation} and
* {@code minExponentDigits}.
* <li><b>2</b>: version for 1.3 and later, which adds four new fields:
* {@code posPrefixPattern}, {@code posSuffixPattern},
* {@code negPrefixPattern}, and {@code negSuffixPattern}.
* <li><b>3</b>: version for 1.5 and later, which adds five new fields:
* {@code maximumIntegerDigits},
* {@code minimumIntegerDigits},
* {@code maximumFractionDigits},
* {@code minimumFractionDigits}, and
* {@code parseBigDecimal}.
* <li><b>4</b>: version for 1.6 and later, which adds one new field:
* {@code roundingMode}.
* </ul>
* @since 1.2
* @serial
*/
private int serialVersionOnStream = currentSerialVersion;
//----------------------------------------------------------------------
// CONSTANTS
//----------------------------------------------------------------------
// ------ Fast-Path for double Constants ------
/** Maximum valid integer value for applying fast-path algorithm */
private static final double MAX_INT_AS_DOUBLE = (double) Integer.MAX_VALUE;
/**
* The digit arrays used in the fast-path methods for collecting digits.
* Using 3 constants arrays of chars ensures a very fast collection of digits
*/
private static class DigitArrays {
static final char[] DigitOnes1000 = new char[1000];
static final char[] DigitTens1000 = new char[1000];
static final char[] DigitHundreds1000 = new char[1000];
// initialize on demand holder class idiom for arrays of digits
static {
int tenIndex = 0;
int hundredIndex = 0;
char digitOne = '0';
char digitTen = '0';
char digitHundred = '0';
for (int i = 0; i < 1000; i++ ) {
DigitOnes1000[i] = digitOne;
if (digitOne == '9')
digitOne = '0';
else
digitOne++;
DigitTens1000[i] = digitTen;
if (i == (tenIndex + 9)) {
tenIndex += 10;
if (digitTen == '9')
digitTen = '0';
else
digitTen++;
}
DigitHundreds1000[i] = digitHundred;
if (i == (hundredIndex + 99)) {
digitHundred++;
hundredIndex += 100;
}
}
}
}
// ------ Fast-Path for double Constants end ------
// Constants for characters used in programmatic (unlocalized) patterns.
private static final char PATTERN_ZERO_DIGIT = '0';
private static final char PATTERN_GROUPING_SEPARATOR = ',';
private static final char PATTERN_DECIMAL_SEPARATOR = '.';
private static final char PATTERN_PER_MILLE = '\u2030';
private static final char PATTERN_PERCENT = '%';
private static final char PATTERN_DIGIT = '#';
private static final char PATTERN_SEPARATOR = ';';
private static final String PATTERN_EXPONENT = "E";
private static final char PATTERN_MINUS = '-';
/**
* The CURRENCY_SIGN is the standard Unicode symbol for currency. It
* is used in patterns and substituted with either the currency symbol,
* or if it is doubled, with the international currency symbol. If the
* CURRENCY_SIGN is seen in a pattern, then the decimal/grouping separators
* are replaced with the monetary decimal/grouping separators.
*
* The CURRENCY_SIGN is not localized.
*/
private static final char CURRENCY_SIGN = '\u00A4';
private static final char QUOTE = '\'';
private static FieldPosition[] EmptyFieldPositionArray = new FieldPosition[0];
// Upper limit on integer and fraction digits for a Java double
static final int DOUBLE_INTEGER_DIGITS = 309;
static final int DOUBLE_FRACTION_DIGITS = 340;
// Upper limit on integer and fraction digits for BigDecimal and BigInteger
static final int MAXIMUM_INTEGER_DIGITS = Integer.MAX_VALUE;
static final int MAXIMUM_FRACTION_DIGITS = Integer.MAX_VALUE;
// Proclaim JDK 1.1 serial compatibility.
@java.io.Serial
static final long serialVersionUID = 864413376551465018L;
}
|