Repository navigation
Expand file tree
/
Copy pathDecimalFormat.java
More file actions
4764 lines (4384 loc) · 201 KB
/
Copy pathDecimalFormat.java
File metadata and controls
4764 lines (4384 loc) · 201 KB
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
/*
* Copyright (c) 1996, 2026, 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.Objects;
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 in a localized manner.
* 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).
*
* <h2>Getting a DecimalFormat</h2>
*
* To obtain a standard decimal format for a specific locale, including the default locale,
* it is recommended to call one of the {@code NumberFormat}
* {@link NumberFormat##factory_methods factory methods}, such as {@link NumberFormat#getInstance()}.
* These factory methods may not always return a {@code DecimalFormat}
* depending on the locale-service provider implementation
* installed. Thus, to use an instance method defined by {@code DecimalFormat},
* the {@code NumberFormat} returned by the factory method should be
* type checked before converted to {@code DecimalFormat}. If the installed locale-sensitive
* service implementation does not support the given {@code Locale}, the parent
* locale chain will be looked up, and a {@code Locale} used that is supported.
*
* <p>If the factory methods are not desired, use one of the constructors such
* as {@link #DecimalFormat(String) DecimalFormat(String pattern)}. See the {@link
* ##patterns Pattern} section for more information on the {@code pattern} parameter.
*
* <h2>Using DecimalFormat</h2>
* The following is an example of formatting and parsing,
* {@snippet lang=java :
* NumberFormat nFmt = NumberFormat.getCurrencyInstance(Locale.US);
* if (nFmt instanceof DecimalFormat dFmt) {
* // pattern match to DecimalFormat to use setPositiveSuffix(String)
* dFmt.setPositiveSuffix(" dollars");
* dFmt.format(100000); // returns "$100,000.00 dollars"
* dFmt.parse("$100,000.00 dollars"); // returns 100000
* }
* }
*
*
* <h2 id="formatting">Formatting and Parsing</h2>
* <h3 id="rounding">Rounding</h3>
*
* When formatting, {@code DecimalFormat} can adjust its rounding using {@link
* #setRoundingMode(RoundingMode)}. By default, it uses
* {@link java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}.
*
* <h3>Digits</h3>
*
* When formatting, {@code DecimalFormat} uses the ten consecutive
* characters starting with the localized zero digit defined in the
* {@code DecimalFormatSymbols} object as digits.
* <p>When parsing, these digits as well as all Unicode decimal digits, as
* defined by {@link Character#digit Character.digit}, are recognized.
*
* <h3 id="digit_limits"> Integer and Fraction Digit Limits </h3>
* The integer and fraction digit limits are set by either applying a {@link ##patterns
* pattern} or using one of the appropriate {@code DecimalFormat} setter methods,
* for example, {@link #setMinimumFractionDigits(int)}. These limits have no impact
* on parsing behavior.
*
* <h3>Special Values</h3>
* <ul>
* <li><p><b>Not a Number</b> ({@code NaN}) is formatted as a string,
* which is typically given as "NaN". This string is determined by {@link
* DecimalFormatSymbols#getNaN()}. This is the only value for which the prefixes
* and suffixes are not attached.
*
* <li><p><b>Infinity</b> is formatted as a string, which is typically given as
* "∞" ({@code U+221E}), with the positive or negative prefixes and suffixes
* attached. This string is determined by {@link DecimalFormatSymbols#getInfinity()}.
*
* <li><p><b>Negative zero</b> ({@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>
* </ul>
*
* <h2><a id="synchronization">Synchronization</a></h2>
*
* <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.
*
* <h2 id="patterns">DecimalFormat Pattern</h2>
*
* 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 various API methods. The symbols are stored in a {@code
* DecimalFormatSymbols} object. When using the {@code NumberFormat} factory
* methods, the pattern and symbols are created from the locale-sensitive service
* implementation installed.
*
* <p> {@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 characters except the {@linkplain ##special_pattern_character
* special pattern characters}
* <i>Suffix:</i>
* Any characters except the {@linkplain ##special_pattern_character
* special pattern 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>
*
* <h3><a id="special_pattern_character">Special Pattern Characters</a></h3>
*
* <p>The special characters in the table below are interpreted syntactically when
* used in the DecimalFormat pattern.
* They must be quoted, unless noted otherwise, if they are to appear in the
* prefix or suffix as literals.
*
* <p> The characters in the {@code Symbol} column are used in non-localized
* patterns. The corresponding characters in the {@code Localized Symbol} column are used
* in localized patterns, with the characters in {@code Symbol} losing their
* syntactical meaning. Two exceptions are the currency sign ({@code U+00A4}) and
* quote ({@code U+0027}), which are not localized.
* <p>
* Non-localized patterns should be used when calling {@link #applyPattern(String)}.
* Localized patterns should be used when calling {@link #applyLocalizedPattern(String)}.
*
* <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">Localized Symbol
* <th scope="col" style="text-align:left">Location
* <th scope="col" style="text-align:left;width:50%">Meaning
* </thead>
* <tbody>
* <tr>
* <th scope="row">{@code 0}
* <td>{@link DecimalFormatSymbols#getZeroDigit()}
* <td>Number
* <td>Digit
* <tr>
* <th scope="row">{@code #}
* <td>{@link DecimalFormatSymbols#getDigit()}
* <td>Number
* <td>Digit, zero shows as absent
* <tr>
* <th scope="row">{@code .}
* <td>{@link DecimalFormatSymbols#getDecimalSeparator()}
* <td>Number
* <td>Decimal separator or monetary decimal separator
* <tr>
* <th scope="row">{@code - (U+002D)}
* <td>{@link DecimalFormatSymbols#getMinusSign()}
* <td>Number
* <td>Minus sign
* <tr>
* <th scope="row">{@code ,}
* <td>{@link DecimalFormatSymbols#getGroupingSeparator()}
* <td>Number
* <td>Grouping separator or monetary grouping separator
* <tr>
* <th scope="row">{@code E}
* <td>{@link DecimalFormatSymbols#getExponentSeparator()}
* <td>Number
* <td>Separates mantissa and exponent in scientific notation. This value
* is case sensitive. <em>Need not be quoted in prefix or suffix.</em>
* <tr>
* <th scope="row">{@code ;}
* <td>{@link DecimalFormatSymbols#getPatternSeparator()}
* <td>Subpattern boundary
* <td>Separates positive and negative subpatterns
* <tr>
* <th scope="row">{@code %}
* <td>{@link DecimalFormatSymbols#getPercent()}
* <td>Prefix or suffix
* <td>Multiply by 100 and show as percentage
* <tr>
* <th scope="row">‰ ({@code U+2030})
* <td>{@link DecimalFormatSymbols#getPerMill()}
* <td>Prefix or suffix
* <td>Multiply by 1000 and show as per mille value
* <tr>
* <th scope="row">¤ ({@code U+00A4})
* <td> n/a (not localized)
* <td>Prefix or suffix
* <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>
* <th scope="row">{@code ' (U+0027)}
* <td> n/a (not localized)
* <td>Prefix or suffix
* <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>Maximum Digits Derivation</h3>
* For any given {@code DecimalFormat} pattern, if the pattern is not
* in scientific notation, the maximum number of integer digits will not be
* derived from the pattern, and instead set to {@link Integer#MAX_VALUE}.
* Otherwise, if the pattern is in scientific notation, the maximum number of
* integer digits will be derived from the pattern. This derivation is detailed
* in the {@link ##scientific_notation Scientific Notation} section. {@link
* #setMaximumIntegerDigits(int)} can be used to manually adjust the maximum
* integer digits.
*
* <h3><a id="negative_subpatterns">Negative Subpatterns</a></h3>
* 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#)"}. In
* {@link NumberFormat##leniency lenient parsing} mode, loose matching of the
* minus sign pattern is enabled, following the LDML’s
* <a href="https://unicode.org/reports/tr35/#Loose_Matching">
* loose matching</a> specification.
*
* <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.
*
* <h3>Grouping Separator</h3>
* <p>The grouping separator is commonly used for thousands, but in some
* locales 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. For example, {@code "#,##,###,####"} == {@code "######,####"} ==
* {@code "##,####,####"}.
*
* <h3 id="scientific_notation">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 <em>maximum integer</em> digits is the sum of '0's and '#'s
* prior to the decimal point. The <em>minimum integer</em> digits is the
* sum of the '0's prior to the decimal point. The <em>maximum fraction</em>
* and <em>minimum fraction</em> digits follow the same rules, but apply to the
* digits after the decimal point but before the exponent. For example, the
* following pattern: {@code "#00.0####E0"} would have a minimum number of
* integer digits = 2("00") and a maximum number of integer digits = 3("#00"). It
* would have a minimum number of fraction digits = 1("0") and a maximum number of fraction
* digits= 5("0####").
*
* <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>For a given number, the amount of significant digits in
* the mantissa can be calculated as such
*
* <blockquote><pre>
* <i>Mantissa Digits:</i>
* min(max(Minimum Pattern Digits, Original Number Digits), Maximum Pattern Digits)
* <i>Minimum pattern Digits:</i>
* <i>Minimum Integer Digits</i> + <i>Minimum Fraction Digits</i>
* <i>Maximum pattern Digits:</i>
* <i>Maximum Integer Digits</i> + <i>Maximum Fraction Digits</i>
* <i>Original Number Digits:</i>
* The amount of significant digits in the number to be formatted
* </pre></blockquote>
*
* This means that generally, a mantissa will have up to the combined maximum integer
* and fraction digits, if the original number itself has enough significant digits. However,
* if there are more minimum pattern digits than significant digits in the original number,
* the mantissa will have significant digits that equals the combined
* minimum integer and fraction digits. The number of significant digits
* does not affect parsing.
*
* <p>It should be noted, that the integer portion of the mantissa will give
* any excess digits to the fraction portion, whether it be for precision or
* for satisfying the total amount of combined minimum digits.
*
* <p>This behavior can be observed in the following example,
* {@snippet lang=java :
* DecimalFormat df = new DecimalFormat("#000.000##E0");
* df.format(12); // returns "12.0000E0"
* df.format(123456789) // returns "1.23456789E8"
* }
*
* <li>Exponential patterns may not contain grouping separators.
* </ul>
*
* @implSpec
* When formatting a {@code Number} other than {@code BigInteger} and
* {@code BigDecimal}, {@code 309} is used as the upper limit for integer digits,
* and {@code 340} as the upper limit for fraction digits. This occurs, even if
* one of the {@code DecimalFormat} getter methods, for example, {@link #getMinimumFractionDigits()}
* returns a numerically greater value.
*
* @spec https://www.unicode.org/reports/tr35
* Unicode Common Locale Data {@literal &} Rules (CLDR)
* @see <a href="http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html">Java Tutorial</a>
* @see NumberFormat
* @see DecimalFormatSymbols
* @see ParsePosition
* @see Locale
* @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.
*
* @apiNote To obtain standard formats for a given locale, use the
* {@code NumberFormat} factory methods such as {@link
* NumberFormat#getNumberInstance(Locale)}. These factories will return the most
* appropriate subclass of NumberFormat for a given locale.
* @see NumberFormat#getInstance(Locale)
* @see NumberFormat#getNumberInstance(Locale)
* @see NumberFormat#getCurrencyInstance(Locale)
* @see NumberFormat#getPercentInstance(Locale)
*/
@SuppressWarnings("this-escape")
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.
* The number of maximum integer digits is usually not derived from the pattern.
* See the note in the {@link ##patterns Patterns} section for more detail.
*
* @apiNote To obtain standard formats for a given locale, use the
* {@code NumberFormat} factory methods such as {@link
* NumberFormat#getNumberInstance(Locale)}. These factories will return the most
* appropriate subclass 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 NumberFormat#getInstance(Locale)
* @see NumberFormat#getNumberInstance(Locale)
* @see NumberFormat#getCurrencyInstance(Locale)
* @see NumberFormat#getPercentInstance(Locale)
*/
@SuppressWarnings("this-escape")
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.
* The number of maximum integer digits is usually not derived from the pattern.
* See the note in the {@link ##patterns Patterns} section for more detail.
*
* @apiNote To obtain standard formats for a given locale, use the
* {@code NumberFormat} factory methods such as {@link
* NumberFormat#getInstance(Locale)} or {@link NumberFormat#getCurrencyInstance(Locale)}.
* 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 NumberFormat#getInstance(Locale)
* @see NumberFormat#getNumberInstance(Locale)
* @see NumberFormat#getCurrencyInstance(Locale)
* @see NumberFormat#getPercentInstance(Locale)
* @see java.text.DecimalFormatSymbols
*/
@SuppressWarnings("this-escape")
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}.
*
* @implSpec 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) {
return switch (number) {
case Long l -> format(l.longValue(), toAppendTo, pos);
case Integer i -> format(i.longValue(), toAppendTo, pos);
case Short s -> format(s.longValue(), toAppendTo, pos);
case Byte b -> format(b.longValue(), toAppendTo, pos);
case AtomicInteger ai -> format(ai.longValue(), toAppendTo, pos);
case AtomicLong al -> format(al.longValue(), toAppendTo, pos);
case BigInteger bi when bi.bitLength() < 64 -> format(bi.longValue(), toAppendTo, pos);
case BigDecimal bd -> format(bd, StringBufFactory.of(toAppendTo), pos).asStringBuffer();
case BigInteger bi -> format(bi, StringBufFactory.of(toAppendTo), pos).asStringBuffer();
case Number n -> format(n.doubleValue(), toAppendTo, pos);
case null, default -> throw new IllegalArgumentException("Cannot format given Object as a Number");
};
}
@Override
final StringBuf format(Object number,
StringBuf toAppendTo,
FieldPosition pos) {
return switch (number) {
case Long l -> format(l.longValue(), toAppendTo, pos);
case Integer i -> format(i.longValue(), toAppendTo, pos);
case Short s -> format(s.longValue(), toAppendTo, pos);
case Byte b -> format(b.longValue(), toAppendTo, pos);
case AtomicInteger ai -> format(ai.longValue(), toAppendTo, pos);
case AtomicLong al -> format(al.longValue(), toAppendTo, pos);
case BigInteger bi when bi.bitLength() < 64 -> format(bi.longValue(), toAppendTo, pos);
case BigDecimal bd -> format(bd, toAppendTo, pos);
case BigInteger bi -> format(bi, toAppendTo, pos);
case Number n -> format(n.doubleValue(), toAppendTo, pos);
case null, default -> 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) {
return format(number, StringBufFactory.of(result), fieldPosition).asStringBuffer();
}
@Override
StringBuf format(double number, StringBuf 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
*/
StringBuf format(double number, StringBuf result,
FieldDelegate delegate) {
boolean nanOrInfinity = handleNaN(number, result, delegate);
if (nanOrInfinity) {
return result;
}
/* 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 = Double.doubleToRawLongBits(number) < 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, StringBuf 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, StringBuf 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;
}
StringBuf doubleSubformat(double number, StringBuf 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, StringBufFactory.of(result), fieldPosition.getFieldDelegate()).asStringBuffer();
}
StringBuf format(long number, StringBuf 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
*/
StringBuf format(long number, StringBuf 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 StringBuf format(BigDecimal number, StringBuf 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
*/
StringBuf format(BigDecimal number, StringBuf 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 StringBuf format(BigInteger number, StringBuf 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
*/
StringBuf format(BigInteger number, StringBuf 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.