Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/text/NumberFormat.java
38829 views
1
/*
2
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
/*
27
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
28
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
29
*
30
* The original version of this source code and documentation is copyrighted
31
* and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
32
* materials are provided under terms of a License Agreement between Taligent
33
* and Sun. This technology is protected by multiple US and International
34
* patents. This notice and attribution to Taligent may not be removed.
35
* Taligent is a registered trademark of Taligent, Inc.
36
*
37
*/
38
39
package java.text;
40
41
import java.io.InvalidObjectException;
42
import java.io.IOException;
43
import java.io.ObjectInputStream;
44
import java.io.ObjectOutputStream;
45
import java.math.BigInteger;
46
import java.math.RoundingMode;
47
import java.text.spi.NumberFormatProvider;
48
import java.util.Currency;
49
import java.util.HashMap;
50
import java.util.Hashtable;
51
import java.util.Locale;
52
import java.util.Map;
53
import java.util.ResourceBundle;
54
import java.util.concurrent.atomic.AtomicInteger;
55
import java.util.concurrent.atomic.AtomicLong;
56
import java.util.spi.LocaleServiceProvider;
57
import sun.util.locale.provider.LocaleProviderAdapter;
58
import sun.util.locale.provider.LocaleServiceProviderPool;
59
60
/**
61
* <code>NumberFormat</code> is the abstract base class for all number
62
* formats. This class provides the interface for formatting and parsing
63
* numbers. <code>NumberFormat</code> also provides methods for determining
64
* which locales have number formats, and what their names are.
65
*
66
* <p>
67
* <code>NumberFormat</code> helps you to format and parse numbers for any locale.
68
* Your code can be completely independent of the locale conventions for
69
* decimal points, thousands-separators, or even the particular decimal
70
* digits used, or whether the number format is even decimal.
71
*
72
* <p>
73
* To format a number for the current Locale, use one of the factory
74
* class methods:
75
* <blockquote>
76
* <pre>{@code
77
* myString = NumberFormat.getInstance().format(myNumber);
78
* }</pre>
79
* </blockquote>
80
* If you are formatting multiple numbers, it is
81
* more efficient to get the format and use it multiple times so that
82
* the system doesn't have to fetch the information about the local
83
* language and country conventions multiple times.
84
* <blockquote>
85
* <pre>{@code
86
* NumberFormat nf = NumberFormat.getInstance();
87
* for (int i = 0; i < myNumber.length; ++i) {
88
* output.println(nf.format(myNumber[i]) + "; ");
89
* }
90
* }</pre>
91
* </blockquote>
92
* To format a number for a different Locale, specify it in the
93
* call to <code>getInstance</code>.
94
* <blockquote>
95
* <pre>{@code
96
* NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
97
* }</pre>
98
* </blockquote>
99
* You can also use a <code>NumberFormat</code> to parse numbers:
100
* <blockquote>
101
* <pre>{@code
102
* myNumber = nf.parse(myString);
103
* }</pre>
104
* </blockquote>
105
* Use <code>getInstance</code> or <code>getNumberInstance</code> to get the
106
* normal number format. Use <code>getIntegerInstance</code> to get an
107
* integer number format. Use <code>getCurrencyInstance</code> to get the
108
* currency number format. And use <code>getPercentInstance</code> to get a
109
* format for displaying percentages. With this format, a fraction like
110
* 0.53 is displayed as 53%.
111
*
112
* <p>
113
* You can also control the display of numbers with such methods as
114
* <code>setMinimumFractionDigits</code>.
115
* If you want even more control over the format or parsing,
116
* or want to give your users more control,
117
* you can try casting the <code>NumberFormat</code> you get from the factory methods
118
* to a <code>DecimalFormat</code>. This will work for the vast majority
119
* of locales; just remember to put it in a <code>try</code> block in case you
120
* encounter an unusual one.
121
*
122
* <p>
123
* NumberFormat and DecimalFormat are designed such that some controls
124
* work for formatting and others work for parsing. The following is
125
* the detailed description for each these control methods,
126
* <p>
127
* setParseIntegerOnly : only affects parsing, e.g.
128
* if true, "3456.78" &rarr; 3456 (and leaves the parse position just after index 6)
129
* if false, "3456.78" &rarr; 3456.78 (and leaves the parse position just after index 8)
130
* This is independent of formatting. If you want to not show a decimal point
131
* where there might be no digits after the decimal point, use
132
* setDecimalSeparatorAlwaysShown.
133
* <p>
134
* setDecimalSeparatorAlwaysShown : only affects formatting, and only where
135
* there might be no digits after the decimal point, such as with a pattern
136
* like "#,##0.##", e.g.,
137
* if true, 3456.00 &rarr; "3,456."
138
* if false, 3456.00 &rarr; "3456"
139
* This is independent of parsing. If you want parsing to stop at the decimal
140
* point, use setParseIntegerOnly.
141
*
142
* <p>
143
* You can also use forms of the <code>parse</code> and <code>format</code>
144
* methods with <code>ParsePosition</code> and <code>FieldPosition</code> to
145
* allow you to:
146
* <ul>
147
* <li> progressively parse through pieces of a string
148
* <li> align the decimal point and other areas
149
* </ul>
150
* For example, you can align numbers in two ways:
151
* <ol>
152
* <li> If you are using a monospaced font with spacing for alignment,
153
* you can pass the <code>FieldPosition</code> in your format call, with
154
* <code>field</code> = <code>INTEGER_FIELD</code>. On output,
155
* <code>getEndIndex</code> will be set to the offset between the
156
* last character of the integer and the decimal. Add
157
* (desiredSpaceCount - getEndIndex) spaces at the front of the string.
158
*
159
* <li> If you are using proportional fonts,
160
* instead of padding with spaces, measure the width
161
* of the string in pixels from the start to <code>getEndIndex</code>.
162
* Then move the pen by
163
* (desiredPixelWidth - widthToAlignmentPoint) before drawing the text.
164
* It also works where there is no decimal, but possibly additional
165
* characters at the end, e.g., with parentheses in negative
166
* numbers: "(12)" for -12.
167
* </ol>
168
*
169
* <h3><a name="synchronization">Synchronization</a></h3>
170
*
171
* <p>
172
* Number formats are generally not synchronized.
173
* It is recommended to create separate format instances for each thread.
174
* If multiple threads access a format concurrently, it must be synchronized
175
* externally.
176
*
177
* @see DecimalFormat
178
* @see ChoiceFormat
179
* @author Mark Davis
180
* @author Helena Shih
181
*/
182
public abstract class NumberFormat extends Format {
183
184
/**
185
* Field constant used to construct a FieldPosition object. Signifies that
186
* the position of the integer part of a formatted number should be returned.
187
* @see java.text.FieldPosition
188
*/
189
public static final int INTEGER_FIELD = 0;
190
191
/**
192
* Field constant used to construct a FieldPosition object. Signifies that
193
* the position of the fraction part of a formatted number should be returned.
194
* @see java.text.FieldPosition
195
*/
196
public static final int FRACTION_FIELD = 1;
197
198
/**
199
* Sole constructor. (For invocation by subclass constructors, typically
200
* implicit.)
201
*/
202
protected NumberFormat() {
203
}
204
205
/**
206
* Formats a number and appends the resulting text to the given string
207
* buffer.
208
* The number can be of any subclass of {@link java.lang.Number}.
209
* <p>
210
* This implementation extracts the number's value using
211
* {@link java.lang.Number#longValue()} for all integral type values that
212
* can be converted to <code>long</code> without loss of information,
213
* including <code>BigInteger</code> values with a
214
* {@link java.math.BigInteger#bitLength() bit length} of less than 64,
215
* and {@link java.lang.Number#doubleValue()} for all other types. It
216
* then calls
217
* {@link #format(long,java.lang.StringBuffer,java.text.FieldPosition)}
218
* or {@link #format(double,java.lang.StringBuffer,java.text.FieldPosition)}.
219
* This may result in loss of magnitude information and precision for
220
* <code>BigInteger</code> and <code>BigDecimal</code> values.
221
* @param number the number to format
222
* @param toAppendTo the <code>StringBuffer</code> to which the formatted
223
* text is to be appended
224
* @param pos On input: an alignment field, if desired.
225
* On output: the offsets of the alignment field.
226
* @return the value passed in as <code>toAppendTo</code>
227
* @exception IllegalArgumentException if <code>number</code> is
228
* null or not an instance of <code>Number</code>.
229
* @exception NullPointerException if <code>toAppendTo</code> or
230
* <code>pos</code> is null
231
* @exception ArithmeticException if rounding is needed with rounding
232
* mode being set to RoundingMode.UNNECESSARY
233
* @see java.text.FieldPosition
234
*/
235
@Override
236
public StringBuffer format(Object number,
237
StringBuffer toAppendTo,
238
FieldPosition pos) {
239
if (number instanceof Long || number instanceof Integer ||
240
number instanceof Short || number instanceof Byte ||
241
number instanceof AtomicInteger || number instanceof AtomicLong ||
242
(number instanceof BigInteger &&
243
((BigInteger)number).bitLength() < 64)) {
244
return format(((Number)number).longValue(), toAppendTo, pos);
245
} else if (number instanceof Number) {
246
return format(((Number)number).doubleValue(), toAppendTo, pos);
247
} else {
248
throw new IllegalArgumentException("Cannot format given Object as a Number");
249
}
250
}
251
252
/**
253
* Parses text from a string to produce a <code>Number</code>.
254
* <p>
255
* The method attempts to parse text starting at the index given by
256
* <code>pos</code>.
257
* If parsing succeeds, then the index of <code>pos</code> is updated
258
* to the index after the last character used (parsing does not necessarily
259
* use all characters up to the end of the string), and the parsed
260
* number is returned. The updated <code>pos</code> can be used to
261
* indicate the starting point for the next call to this method.
262
* If an error occurs, then the index of <code>pos</code> is not
263
* changed, the error index of <code>pos</code> is set to the index of
264
* the character where the error occurred, and null is returned.
265
* <p>
266
* See the {@link #parse(String, ParsePosition)} method for more information
267
* on number parsing.
268
*
269
* @param source A <code>String</code>, part of which should be parsed.
270
* @param pos A <code>ParsePosition</code> object with index and error
271
* index information as described above.
272
* @return A <code>Number</code> parsed from the string. In case of
273
* error, returns null.
274
* @exception NullPointerException if <code>pos</code> is null.
275
*/
276
@Override
277
public final Object parseObject(String source, ParsePosition pos) {
278
return parse(source, pos);
279
}
280
281
/**
282
* Specialization of format.
283
*
284
* @param number the double number to format
285
* @return the formatted String
286
* @exception ArithmeticException if rounding is needed with rounding
287
* mode being set to RoundingMode.UNNECESSARY
288
* @see java.text.Format#format
289
*/
290
public final String format(double number) {
291
// Use fast-path for double result if that works
292
String result = fastFormat(number);
293
if (result != null)
294
return result;
295
296
return format(number, new StringBuffer(),
297
DontCareFieldPosition.INSTANCE).toString();
298
}
299
300
/*
301
* fastFormat() is supposed to be implemented in concrete subclasses only.
302
* Default implem always returns null.
303
*/
304
String fastFormat(double number) { return null; }
305
306
/**
307
* Specialization of format.
308
*
309
* @param number the long number to format
310
* @return the formatted String
311
* @exception ArithmeticException if rounding is needed with rounding
312
* mode being set to RoundingMode.UNNECESSARY
313
* @see java.text.Format#format
314
*/
315
public final String format(long number) {
316
return format(number, new StringBuffer(),
317
DontCareFieldPosition.INSTANCE).toString();
318
}
319
320
/**
321
* Specialization of format.
322
*
323
* @param number the double number to format
324
* @param toAppendTo the StringBuffer to which the formatted text is to be
325
* appended
326
* @param pos the field position
327
* @return the formatted StringBuffer
328
* @exception ArithmeticException if rounding is needed with rounding
329
* mode being set to RoundingMode.UNNECESSARY
330
* @see java.text.Format#format
331
*/
332
public abstract StringBuffer format(double number,
333
StringBuffer toAppendTo,
334
FieldPosition pos);
335
336
/**
337
* Specialization of format.
338
*
339
* @param number the long number to format
340
* @param toAppendTo the StringBuffer to which the formatted text is to be
341
* appended
342
* @param pos the field position
343
* @return the formatted StringBuffer
344
* @exception ArithmeticException if rounding is needed with rounding
345
* mode being set to RoundingMode.UNNECESSARY
346
* @see java.text.Format#format
347
*/
348
public abstract StringBuffer format(long number,
349
StringBuffer toAppendTo,
350
FieldPosition pos);
351
352
/**
353
* Returns a Long if possible (e.g., within the range [Long.MIN_VALUE,
354
* Long.MAX_VALUE] and with no decimals), otherwise a Double.
355
* If IntegerOnly is set, will stop at a decimal
356
* point (or equivalent; e.g., for rational numbers "1 2/3", will stop
357
* after the 1).
358
* Does not throw an exception; if no object can be parsed, index is
359
* unchanged!
360
*
361
* @param source the String to parse
362
* @param parsePosition the parse position
363
* @return the parsed value
364
* @see java.text.NumberFormat#isParseIntegerOnly
365
* @see java.text.Format#parseObject
366
*/
367
public abstract Number parse(String source, ParsePosition parsePosition);
368
369
/**
370
* Parses text from the beginning of the given string to produce a number.
371
* The method may not use the entire text of the given string.
372
* <p>
373
* See the {@link #parse(String, ParsePosition)} method for more information
374
* on number parsing.
375
*
376
* @param source A <code>String</code> whose beginning should be parsed.
377
* @return A <code>Number</code> parsed from the string.
378
* @exception ParseException if the beginning of the specified string
379
* cannot be parsed.
380
*/
381
public Number parse(String source) throws ParseException {
382
ParsePosition parsePosition = new ParsePosition(0);
383
Number result = parse(source, parsePosition);
384
if (parsePosition.index == 0) {
385
throw new ParseException("Unparseable number: \"" + source + "\"",
386
parsePosition.errorIndex);
387
}
388
return result;
389
}
390
391
/**
392
* Returns true if this format will parse numbers as integers only.
393
* For example in the English locale, with ParseIntegerOnly true, the
394
* string "1234." would be parsed as the integer value 1234 and parsing
395
* would stop at the "." character. Of course, the exact format accepted
396
* by the parse operation is locale dependant and determined by sub-classes
397
* of NumberFormat.
398
*
399
* @return {@code true} if numbers should be parsed as integers only;
400
* {@code false} otherwise
401
*/
402
public boolean isParseIntegerOnly() {
403
return parseIntegerOnly;
404
}
405
406
/**
407
* Sets whether or not numbers should be parsed as integers only.
408
*
409
* @param value {@code true} if numbers should be parsed as integers only;
410
* {@code false} otherwise
411
* @see #isParseIntegerOnly
412
*/
413
public void setParseIntegerOnly(boolean value) {
414
parseIntegerOnly = value;
415
}
416
417
//============== Locale Stuff =====================
418
419
/**
420
* Returns a general-purpose number format for the current default
421
* {@link java.util.Locale.Category#FORMAT FORMAT} locale.
422
* This is the same as calling
423
* {@link #getNumberInstance() getNumberInstance()}.
424
*
425
* @return the {@code NumberFormat} instance for general-purpose number
426
* formatting
427
*/
428
public final static NumberFormat getInstance() {
429
return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE);
430
}
431
432
/**
433
* Returns a general-purpose number format for the specified locale.
434
* This is the same as calling
435
* {@link #getNumberInstance(java.util.Locale) getNumberInstance(inLocale)}.
436
*
437
* @param inLocale the desired locale
438
* @return the {@code NumberFormat} instance for general-purpose number
439
* formatting
440
*/
441
public static NumberFormat getInstance(Locale inLocale) {
442
return getInstance(inLocale, NUMBERSTYLE);
443
}
444
445
/**
446
* Returns a general-purpose number format for the current default
447
* {@link java.util.Locale.Category#FORMAT FORMAT} locale.
448
* <p>This is equivalent to calling
449
* {@link #getNumberInstance(Locale)
450
* getNumberInstance(Locale.getDefault(Locale.Category.FORMAT))}.
451
*
452
* @return the {@code NumberFormat} instance for general-purpose number
453
* formatting
454
* @see java.util.Locale#getDefault(java.util.Locale.Category)
455
* @see java.util.Locale.Category#FORMAT
456
*/
457
public final static NumberFormat getNumberInstance() {
458
return getInstance(Locale.getDefault(Locale.Category.FORMAT), NUMBERSTYLE);
459
}
460
461
/**
462
* Returns a general-purpose number format for the specified locale.
463
*
464
* @param inLocale the desired locale
465
* @return the {@code NumberFormat} instance for general-purpose number
466
* formatting
467
*/
468
public static NumberFormat getNumberInstance(Locale inLocale) {
469
return getInstance(inLocale, NUMBERSTYLE);
470
}
471
472
/**
473
* Returns an integer number format for the current default
474
* {@link java.util.Locale.Category#FORMAT FORMAT} locale. The
475
* returned number format is configured to round floating point numbers
476
* to the nearest integer using half-even rounding (see {@link
477
* java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}) for formatting,
478
* and to parse only the integer part of an input string (see {@link
479
* #isParseIntegerOnly isParseIntegerOnly}).
480
* <p>This is equivalent to calling
481
* {@link #getIntegerInstance(Locale)
482
* getIntegerInstance(Locale.getDefault(Locale.Category.FORMAT))}.
483
*
484
* @see #getRoundingMode()
485
* @see java.util.Locale#getDefault(java.util.Locale.Category)
486
* @see java.util.Locale.Category#FORMAT
487
* @return a number format for integer values
488
* @since 1.4
489
*/
490
public final static NumberFormat getIntegerInstance() {
491
return getInstance(Locale.getDefault(Locale.Category.FORMAT), INTEGERSTYLE);
492
}
493
494
/**
495
* Returns an integer number format for the specified locale. The
496
* returned number format is configured to round floating point numbers
497
* to the nearest integer using half-even rounding (see {@link
498
* java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}) for formatting,
499
* and to parse only the integer part of an input string (see {@link
500
* #isParseIntegerOnly isParseIntegerOnly}).
501
*
502
* @param inLocale the desired locale
503
* @see #getRoundingMode()
504
* @return a number format for integer values
505
* @since 1.4
506
*/
507
public static NumberFormat getIntegerInstance(Locale inLocale) {
508
return getInstance(inLocale, INTEGERSTYLE);
509
}
510
511
/**
512
* Returns a currency format for the current default
513
* {@link java.util.Locale.Category#FORMAT FORMAT} locale.
514
* <p>This is equivalent to calling
515
* {@link #getCurrencyInstance(Locale)
516
* getCurrencyInstance(Locale.getDefault(Locale.Category.FORMAT))}.
517
*
518
* @return the {@code NumberFormat} instance for currency formatting
519
* @see java.util.Locale#getDefault(java.util.Locale.Category)
520
* @see java.util.Locale.Category#FORMAT
521
*/
522
public final static NumberFormat getCurrencyInstance() {
523
return getInstance(Locale.getDefault(Locale.Category.FORMAT), CURRENCYSTYLE);
524
}
525
526
/**
527
* Returns a currency format for the specified locale.
528
*
529
* @param inLocale the desired locale
530
* @return the {@code NumberFormat} instance for currency formatting
531
*/
532
public static NumberFormat getCurrencyInstance(Locale inLocale) {
533
return getInstance(inLocale, CURRENCYSTYLE);
534
}
535
536
/**
537
* Returns a percentage format for the current default
538
* {@link java.util.Locale.Category#FORMAT FORMAT} locale.
539
* <p>This is equivalent to calling
540
* {@link #getPercentInstance(Locale)
541
* getPercentInstance(Locale.getDefault(Locale.Category.FORMAT))}.
542
*
543
* @return the {@code NumberFormat} instance for percentage formatting
544
* @see java.util.Locale#getDefault(java.util.Locale.Category)
545
* @see java.util.Locale.Category#FORMAT
546
*/
547
public final static NumberFormat getPercentInstance() {
548
return getInstance(Locale.getDefault(Locale.Category.FORMAT), PERCENTSTYLE);
549
}
550
551
/**
552
* Returns a percentage format for the specified locale.
553
*
554
* @param inLocale the desired locale
555
* @return the {@code NumberFormat} instance for percentage formatting
556
*/
557
public static NumberFormat getPercentInstance(Locale inLocale) {
558
return getInstance(inLocale, PERCENTSTYLE);
559
}
560
561
/**
562
* Returns a scientific format for the current default locale.
563
*/
564
/*public*/ final static NumberFormat getScientificInstance() {
565
return getInstance(Locale.getDefault(Locale.Category.FORMAT), SCIENTIFICSTYLE);
566
}
567
568
/**
569
* Returns a scientific format for the specified locale.
570
*
571
* @param inLocale the desired locale
572
*/
573
/*public*/ static NumberFormat getScientificInstance(Locale inLocale) {
574
return getInstance(inLocale, SCIENTIFICSTYLE);
575
}
576
577
/**
578
* Returns an array of all locales for which the
579
* <code>get*Instance</code> methods of this class can return
580
* localized instances.
581
* The returned array represents the union of locales supported by the Java
582
* runtime and by installed
583
* {@link java.text.spi.NumberFormatProvider NumberFormatProvider} implementations.
584
* It must contain at least a <code>Locale</code> instance equal to
585
* {@link java.util.Locale#US Locale.US}.
586
*
587
* @return An array of locales for which localized
588
* <code>NumberFormat</code> instances are available.
589
*/
590
public static Locale[] getAvailableLocales() {
591
LocaleServiceProviderPool pool =
592
LocaleServiceProviderPool.getPool(NumberFormatProvider.class);
593
return pool.getAvailableLocales();
594
}
595
596
/**
597
* Overrides hashCode.
598
*/
599
@Override
600
public int hashCode() {
601
return maximumIntegerDigits * 37 + maxFractionDigits;
602
// just enough fields for a reasonable distribution
603
}
604
605
/**
606
* Overrides equals.
607
*/
608
@Override
609
public boolean equals(Object obj) {
610
if (obj == null) {
611
return false;
612
}
613
if (this == obj) {
614
return true;
615
}
616
if (getClass() != obj.getClass()) {
617
return false;
618
}
619
NumberFormat other = (NumberFormat) obj;
620
return (maximumIntegerDigits == other.maximumIntegerDigits
621
&& minimumIntegerDigits == other.minimumIntegerDigits
622
&& maximumFractionDigits == other.maximumFractionDigits
623
&& minimumFractionDigits == other.minimumFractionDigits
624
&& groupingUsed == other.groupingUsed
625
&& parseIntegerOnly == other.parseIntegerOnly);
626
}
627
628
/**
629
* Overrides Cloneable.
630
*/
631
@Override
632
public Object clone() {
633
NumberFormat other = (NumberFormat) super.clone();
634
return other;
635
}
636
637
/**
638
* Returns true if grouping is used in this format. For example, in the
639
* English locale, with grouping on, the number 1234567 might be formatted
640
* as "1,234,567". The grouping separator as well as the size of each group
641
* is locale dependant and is determined by sub-classes of NumberFormat.
642
*
643
* @return {@code true} if grouping is used;
644
* {@code false} otherwise
645
* @see #setGroupingUsed
646
*/
647
public boolean isGroupingUsed() {
648
return groupingUsed;
649
}
650
651
/**
652
* Set whether or not grouping will be used in this format.
653
*
654
* @param newValue {@code true} if grouping is used;
655
* {@code false} otherwise
656
* @see #isGroupingUsed
657
*/
658
public void setGroupingUsed(boolean newValue) {
659
groupingUsed = newValue;
660
}
661
662
/**
663
* Returns the maximum number of digits allowed in the integer portion of a
664
* number.
665
*
666
* @return the maximum number of digits
667
* @see #setMaximumIntegerDigits
668
*/
669
public int getMaximumIntegerDigits() {
670
return maximumIntegerDigits;
671
}
672
673
/**
674
* Sets the maximum number of digits allowed in the integer portion of a
675
* number. maximumIntegerDigits must be &ge; minimumIntegerDigits. If the
676
* new value for maximumIntegerDigits is less than the current value
677
* of minimumIntegerDigits, then minimumIntegerDigits will also be set to
678
* the new value.
679
*
680
* @param newValue the maximum number of integer digits to be shown; if
681
* less than zero, then zero is used. The concrete subclass may enforce an
682
* upper limit to this value appropriate to the numeric type being formatted.
683
* @see #getMaximumIntegerDigits
684
*/
685
public void setMaximumIntegerDigits(int newValue) {
686
maximumIntegerDigits = Math.max(0,newValue);
687
if (minimumIntegerDigits > maximumIntegerDigits) {
688
minimumIntegerDigits = maximumIntegerDigits;
689
}
690
}
691
692
/**
693
* Returns the minimum number of digits allowed in the integer portion of a
694
* number.
695
*
696
* @return the minimum number of digits
697
* @see #setMinimumIntegerDigits
698
*/
699
public int getMinimumIntegerDigits() {
700
return minimumIntegerDigits;
701
}
702
703
/**
704
* Sets the minimum number of digits allowed in the integer portion of a
705
* number. minimumIntegerDigits must be &le; maximumIntegerDigits. If the
706
* new value for minimumIntegerDigits exceeds the current value
707
* of maximumIntegerDigits, then maximumIntegerDigits will also be set to
708
* the new value
709
*
710
* @param newValue the minimum number of integer digits to be shown; if
711
* less than zero, then zero is used. The concrete subclass may enforce an
712
* upper limit to this value appropriate to the numeric type being formatted.
713
* @see #getMinimumIntegerDigits
714
*/
715
public void setMinimumIntegerDigits(int newValue) {
716
minimumIntegerDigits = Math.max(0,newValue);
717
if (minimumIntegerDigits > maximumIntegerDigits) {
718
maximumIntegerDigits = minimumIntegerDigits;
719
}
720
}
721
722
/**
723
* Returns the maximum number of digits allowed in the fraction portion of a
724
* number.
725
*
726
* @return the maximum number of digits.
727
* @see #setMaximumFractionDigits
728
*/
729
public int getMaximumFractionDigits() {
730
return maximumFractionDigits;
731
}
732
733
/**
734
* Sets the maximum number of digits allowed in the fraction portion of a
735
* number. maximumFractionDigits must be &ge; minimumFractionDigits. If the
736
* new value for maximumFractionDigits is less than the current value
737
* of minimumFractionDigits, then minimumFractionDigits will also be set to
738
* the new value.
739
*
740
* @param newValue the maximum number of fraction digits to be shown; if
741
* less than zero, then zero is used. The concrete subclass may enforce an
742
* upper limit to this value appropriate to the numeric type being formatted.
743
* @see #getMaximumFractionDigits
744
*/
745
public void setMaximumFractionDigits(int newValue) {
746
maximumFractionDigits = Math.max(0,newValue);
747
if (maximumFractionDigits < minimumFractionDigits) {
748
minimumFractionDigits = maximumFractionDigits;
749
}
750
}
751
752
/**
753
* Returns the minimum number of digits allowed in the fraction portion of a
754
* number.
755
*
756
* @return the minimum number of digits
757
* @see #setMinimumFractionDigits
758
*/
759
public int getMinimumFractionDigits() {
760
return minimumFractionDigits;
761
}
762
763
/**
764
* Sets the minimum number of digits allowed in the fraction portion of a
765
* number. minimumFractionDigits must be &le; maximumFractionDigits. If the
766
* new value for minimumFractionDigits exceeds the current value
767
* of maximumFractionDigits, then maximumIntegerDigits will also be set to
768
* the new value
769
*
770
* @param newValue the minimum number of fraction digits to be shown; if
771
* less than zero, then zero is used. The concrete subclass may enforce an
772
* upper limit to this value appropriate to the numeric type being formatted.
773
* @see #getMinimumFractionDigits
774
*/
775
public void setMinimumFractionDigits(int newValue) {
776
minimumFractionDigits = Math.max(0,newValue);
777
if (maximumFractionDigits < minimumFractionDigits) {
778
maximumFractionDigits = minimumFractionDigits;
779
}
780
}
781
782
/**
783
* Gets the currency used by this number format when formatting
784
* currency values. The initial value is derived in a locale dependent
785
* way. The returned value may be null if no valid
786
* currency could be determined and no currency has been set using
787
* {@link #setCurrency(java.util.Currency) setCurrency}.
788
* <p>
789
* The default implementation throws
790
* <code>UnsupportedOperationException</code>.
791
*
792
* @return the currency used by this number format, or <code>null</code>
793
* @exception UnsupportedOperationException if the number format class
794
* doesn't implement currency formatting
795
* @since 1.4
796
*/
797
public Currency getCurrency() {
798
throw new UnsupportedOperationException();
799
}
800
801
/**
802
* Sets the currency used by this number format when formatting
803
* currency values. This does not update the minimum or maximum
804
* number of fraction digits used by the number format.
805
* <p>
806
* The default implementation throws
807
* <code>UnsupportedOperationException</code>.
808
*
809
* @param currency the new currency to be used by this number format
810
* @exception UnsupportedOperationException if the number format class
811
* doesn't implement currency formatting
812
* @exception NullPointerException if <code>currency</code> is null
813
* @since 1.4
814
*/
815
public void setCurrency(Currency currency) {
816
throw new UnsupportedOperationException();
817
}
818
819
/**
820
* Gets the {@link java.math.RoundingMode} used in this NumberFormat.
821
* The default implementation of this method in NumberFormat
822
* always throws {@link java.lang.UnsupportedOperationException}.
823
* Subclasses which handle different rounding modes should override
824
* this method.
825
*
826
* @exception UnsupportedOperationException The default implementation
827
* always throws this exception
828
* @return The <code>RoundingMode</code> used for this NumberFormat.
829
* @see #setRoundingMode(RoundingMode)
830
* @since 1.6
831
*/
832
public RoundingMode getRoundingMode() {
833
throw new UnsupportedOperationException();
834
}
835
836
/**
837
* Sets the {@link java.math.RoundingMode} used in this NumberFormat.
838
* The default implementation of this method in NumberFormat always
839
* throws {@link java.lang.UnsupportedOperationException}.
840
* Subclasses which handle different rounding modes should override
841
* this method.
842
*
843
* @exception UnsupportedOperationException The default implementation
844
* always throws this exception
845
* @exception NullPointerException if <code>roundingMode</code> is null
846
* @param roundingMode The <code>RoundingMode</code> to be used
847
* @see #getRoundingMode()
848
* @since 1.6
849
*/
850
public void setRoundingMode(RoundingMode roundingMode) {
851
throw new UnsupportedOperationException();
852
}
853
854
// =======================privates===============================
855
856
private static NumberFormat getInstance(Locale desiredLocale,
857
int choice) {
858
LocaleProviderAdapter adapter;
859
adapter = LocaleProviderAdapter.getAdapter(NumberFormatProvider.class,
860
desiredLocale);
861
NumberFormat numberFormat = getInstance(adapter, desiredLocale, choice);
862
if (numberFormat == null) {
863
numberFormat = getInstance(LocaleProviderAdapter.forJRE(),
864
desiredLocale, choice);
865
}
866
return numberFormat;
867
}
868
869
private static NumberFormat getInstance(LocaleProviderAdapter adapter,
870
Locale locale, int choice) {
871
NumberFormatProvider provider = adapter.getNumberFormatProvider();
872
NumberFormat numberFormat = null;
873
switch (choice) {
874
case NUMBERSTYLE:
875
numberFormat = provider.getNumberInstance(locale);
876
break;
877
case PERCENTSTYLE:
878
numberFormat = provider.getPercentInstance(locale);
879
break;
880
case CURRENCYSTYLE:
881
numberFormat = provider.getCurrencyInstance(locale);
882
break;
883
case INTEGERSTYLE:
884
numberFormat = provider.getIntegerInstance(locale);
885
break;
886
}
887
return numberFormat;
888
}
889
890
/**
891
* First, read in the default serializable data.
892
*
893
* Then, if <code>serialVersionOnStream</code> is less than 1, indicating that
894
* the stream was written by JDK 1.1,
895
* set the <code>int</code> fields such as <code>maximumIntegerDigits</code>
896
* to be equal to the <code>byte</code> fields such as <code>maxIntegerDigits</code>,
897
* since the <code>int</code> fields were not present in JDK 1.1.
898
* Finally, set serialVersionOnStream back to the maximum allowed value so that
899
* default serialization will work properly if this object is streamed out again.
900
*
901
* <p>If <code>minimumIntegerDigits</code> is greater than
902
* <code>maximumIntegerDigits</code> or <code>minimumFractionDigits</code>
903
* is greater than <code>maximumFractionDigits</code>, then the stream data
904
* is invalid and this method throws an <code>InvalidObjectException</code>.
905
* In addition, if any of these values is negative, then this method throws
906
* an <code>InvalidObjectException</code>.
907
*
908
* @since 1.2
909
*/
910
private void readObject(ObjectInputStream stream)
911
throws IOException, ClassNotFoundException
912
{
913
stream.defaultReadObject();
914
if (serialVersionOnStream < 1) {
915
// Didn't have additional int fields, reassign to use them.
916
maximumIntegerDigits = maxIntegerDigits;
917
minimumIntegerDigits = minIntegerDigits;
918
maximumFractionDigits = maxFractionDigits;
919
minimumFractionDigits = minFractionDigits;
920
}
921
if (minimumIntegerDigits > maximumIntegerDigits ||
922
minimumFractionDigits > maximumFractionDigits ||
923
minimumIntegerDigits < 0 || minimumFractionDigits < 0) {
924
throw new InvalidObjectException("Digit count range invalid");
925
}
926
serialVersionOnStream = currentSerialVersion;
927
}
928
929
/**
930
* Write out the default serializable data, after first setting
931
* the <code>byte</code> fields such as <code>maxIntegerDigits</code> to be
932
* equal to the <code>int</code> fields such as <code>maximumIntegerDigits</code>
933
* (or to <code>Byte.MAX_VALUE</code>, whichever is smaller), for compatibility
934
* with the JDK 1.1 version of the stream format.
935
*
936
* @since 1.2
937
*/
938
private void writeObject(ObjectOutputStream stream)
939
throws IOException
940
{
941
maxIntegerDigits = (maximumIntegerDigits > Byte.MAX_VALUE) ?
942
Byte.MAX_VALUE : (byte)maximumIntegerDigits;
943
minIntegerDigits = (minimumIntegerDigits > Byte.MAX_VALUE) ?
944
Byte.MAX_VALUE : (byte)minimumIntegerDigits;
945
maxFractionDigits = (maximumFractionDigits > Byte.MAX_VALUE) ?
946
Byte.MAX_VALUE : (byte)maximumFractionDigits;
947
minFractionDigits = (minimumFractionDigits > Byte.MAX_VALUE) ?
948
Byte.MAX_VALUE : (byte)minimumFractionDigits;
949
stream.defaultWriteObject();
950
}
951
952
// Constants used by factory methods to specify a style of format.
953
private static final int NUMBERSTYLE = 0;
954
private static final int CURRENCYSTYLE = 1;
955
private static final int PERCENTSTYLE = 2;
956
private static final int SCIENTIFICSTYLE = 3;
957
private static final int INTEGERSTYLE = 4;
958
959
/**
960
* True if the grouping (i.e. thousands) separator is used when
961
* formatting and parsing numbers.
962
*
963
* @serial
964
* @see #isGroupingUsed
965
*/
966
private boolean groupingUsed = true;
967
968
/**
969
* The maximum number of digits allowed in the integer portion of a
970
* number. <code>maxIntegerDigits</code> must be greater than or equal to
971
* <code>minIntegerDigits</code>.
972
* <p>
973
* <strong>Note:</strong> This field exists only for serialization
974
* compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new
975
* <code>int</code> field <code>maximumIntegerDigits</code> is used instead.
976
* When writing to a stream, <code>maxIntegerDigits</code> is set to
977
* <code>maximumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>,
978
* whichever is smaller. When reading from a stream, this field is used
979
* only if <code>serialVersionOnStream</code> is less than 1.
980
*
981
* @serial
982
* @see #getMaximumIntegerDigits
983
*/
984
private byte maxIntegerDigits = 40;
985
986
/**
987
* The minimum number of digits allowed in the integer portion of a
988
* number. <code>minimumIntegerDigits</code> must be less than or equal to
989
* <code>maximumIntegerDigits</code>.
990
* <p>
991
* <strong>Note:</strong> This field exists only for serialization
992
* compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new
993
* <code>int</code> field <code>minimumIntegerDigits</code> is used instead.
994
* When writing to a stream, <code>minIntegerDigits</code> is set to
995
* <code>minimumIntegerDigits</code> or <code>Byte.MAX_VALUE</code>,
996
* whichever is smaller. When reading from a stream, this field is used
997
* only if <code>serialVersionOnStream</code> is less than 1.
998
*
999
* @serial
1000
* @see #getMinimumIntegerDigits
1001
*/
1002
private byte minIntegerDigits = 1;
1003
1004
/**
1005
* The maximum number of digits allowed in the fractional portion of a
1006
* number. <code>maximumFractionDigits</code> must be greater than or equal to
1007
* <code>minimumFractionDigits</code>.
1008
* <p>
1009
* <strong>Note:</strong> This field exists only for serialization
1010
* compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new
1011
* <code>int</code> field <code>maximumFractionDigits</code> is used instead.
1012
* When writing to a stream, <code>maxFractionDigits</code> is set to
1013
* <code>maximumFractionDigits</code> or <code>Byte.MAX_VALUE</code>,
1014
* whichever is smaller. When reading from a stream, this field is used
1015
* only if <code>serialVersionOnStream</code> is less than 1.
1016
*
1017
* @serial
1018
* @see #getMaximumFractionDigits
1019
*/
1020
private byte maxFractionDigits = 3; // invariant, >= minFractionDigits
1021
1022
/**
1023
* The minimum number of digits allowed in the fractional portion of a
1024
* number. <code>minimumFractionDigits</code> must be less than or equal to
1025
* <code>maximumFractionDigits</code>.
1026
* <p>
1027
* <strong>Note:</strong> This field exists only for serialization
1028
* compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new
1029
* <code>int</code> field <code>minimumFractionDigits</code> is used instead.
1030
* When writing to a stream, <code>minFractionDigits</code> is set to
1031
* <code>minimumFractionDigits</code> or <code>Byte.MAX_VALUE</code>,
1032
* whichever is smaller. When reading from a stream, this field is used
1033
* only if <code>serialVersionOnStream</code> is less than 1.
1034
*
1035
* @serial
1036
* @see #getMinimumFractionDigits
1037
*/
1038
private byte minFractionDigits = 0;
1039
1040
/**
1041
* True if this format will parse numbers as integers only.
1042
*
1043
* @serial
1044
* @see #isParseIntegerOnly
1045
*/
1046
private boolean parseIntegerOnly = false;
1047
1048
// new fields for 1.2. byte is too small for integer digits.
1049
1050
/**
1051
* The maximum number of digits allowed in the integer portion of a
1052
* number. <code>maximumIntegerDigits</code> must be greater than or equal to
1053
* <code>minimumIntegerDigits</code>.
1054
*
1055
* @serial
1056
* @since 1.2
1057
* @see #getMaximumIntegerDigits
1058
*/
1059
private int maximumIntegerDigits = 40;
1060
1061
/**
1062
* The minimum number of digits allowed in the integer portion of a
1063
* number. <code>minimumIntegerDigits</code> must be less than or equal to
1064
* <code>maximumIntegerDigits</code>.
1065
*
1066
* @serial
1067
* @since 1.2
1068
* @see #getMinimumIntegerDigits
1069
*/
1070
private int minimumIntegerDigits = 1;
1071
1072
/**
1073
* The maximum number of digits allowed in the fractional portion of a
1074
* number. <code>maximumFractionDigits</code> must be greater than or equal to
1075
* <code>minimumFractionDigits</code>.
1076
*
1077
* @serial
1078
* @since 1.2
1079
* @see #getMaximumFractionDigits
1080
*/
1081
private int maximumFractionDigits = 3; // invariant, >= minFractionDigits
1082
1083
/**
1084
* The minimum number of digits allowed in the fractional portion of a
1085
* number. <code>minimumFractionDigits</code> must be less than or equal to
1086
* <code>maximumFractionDigits</code>.
1087
*
1088
* @serial
1089
* @since 1.2
1090
* @see #getMinimumFractionDigits
1091
*/
1092
private int minimumFractionDigits = 0;
1093
1094
static final int currentSerialVersion = 1;
1095
1096
/**
1097
* Describes the version of <code>NumberFormat</code> present on the stream.
1098
* Possible values are:
1099
* <ul>
1100
* <li><b>0</b> (or uninitialized): the JDK 1.1 version of the stream format.
1101
* In this version, the <code>int</code> fields such as
1102
* <code>maximumIntegerDigits</code> were not present, and the <code>byte</code>
1103
* fields such as <code>maxIntegerDigits</code> are used instead.
1104
*
1105
* <li><b>1</b>: the 1.2 version of the stream format. The values of the
1106
* <code>byte</code> fields such as <code>maxIntegerDigits</code> are ignored,
1107
* and the <code>int</code> fields such as <code>maximumIntegerDigits</code>
1108
* are used instead.
1109
* </ul>
1110
* When streaming out a <code>NumberFormat</code>, the most recent format
1111
* (corresponding to the highest allowable <code>serialVersionOnStream</code>)
1112
* is always written.
1113
*
1114
* @serial
1115
* @since 1.2
1116
*/
1117
private int serialVersionOnStream = currentSerialVersion;
1118
1119
// Removed "implements Cloneable" clause. Needs to update serialization
1120
// ID for backward compatibility.
1121
static final long serialVersionUID = -2308460125733713944L;
1122
1123
1124
//
1125
// class for AttributedCharacterIterator attributes
1126
//
1127
/**
1128
* Defines constants that are used as attribute keys in the
1129
* <code>AttributedCharacterIterator</code> returned
1130
* from <code>NumberFormat.formatToCharacterIterator</code> and as
1131
* field identifiers in <code>FieldPosition</code>.
1132
*
1133
* @since 1.4
1134
*/
1135
public static class Field extends Format.Field {
1136
1137
// Proclaim serial compatibility with 1.4 FCS
1138
private static final long serialVersionUID = 7494728892700160890L;
1139
1140
// table of all instances in this class, used by readResolve
1141
private static final Map<String, Field> instanceMap = new HashMap<>(11);
1142
1143
/**
1144
* Creates a Field instance with the specified
1145
* name.
1146
*
1147
* @param name Name of the attribute
1148
*/
1149
protected Field(String name) {
1150
super(name);
1151
if (this.getClass() == NumberFormat.Field.class) {
1152
instanceMap.put(name, this);
1153
}
1154
}
1155
1156
/**
1157
* Resolves instances being deserialized to the predefined constants.
1158
*
1159
* @throws InvalidObjectException if the constant could not be resolved.
1160
* @return resolved NumberFormat.Field constant
1161
*/
1162
@Override
1163
protected Object readResolve() throws InvalidObjectException {
1164
if (this.getClass() != NumberFormat.Field.class) {
1165
throw new InvalidObjectException("subclass didn't correctly implement readResolve");
1166
}
1167
1168
Object instance = instanceMap.get(getName());
1169
if (instance != null) {
1170
return instance;
1171
} else {
1172
throw new InvalidObjectException("unknown attribute name");
1173
}
1174
}
1175
1176
/**
1177
* Constant identifying the integer field.
1178
*/
1179
public static final Field INTEGER = new Field("integer");
1180
1181
/**
1182
* Constant identifying the fraction field.
1183
*/
1184
public static final Field FRACTION = new Field("fraction");
1185
1186
/**
1187
* Constant identifying the exponent field.
1188
*/
1189
public static final Field EXPONENT = new Field("exponent");
1190
1191
/**
1192
* Constant identifying the decimal separator field.
1193
*/
1194
public static final Field DECIMAL_SEPARATOR =
1195
new Field("decimal separator");
1196
1197
/**
1198
* Constant identifying the sign field.
1199
*/
1200
public static final Field SIGN = new Field("sign");
1201
1202
/**
1203
* Constant identifying the grouping separator field.
1204
*/
1205
public static final Field GROUPING_SEPARATOR =
1206
new Field("grouping separator");
1207
1208
/**
1209
* Constant identifying the exponent symbol field.
1210
*/
1211
public static final Field EXPONENT_SYMBOL = new
1212
Field("exponent symbol");
1213
1214
/**
1215
* Constant identifying the percent field.
1216
*/
1217
public static final Field PERCENT = new Field("percent");
1218
1219
/**
1220
* Constant identifying the permille field.
1221
*/
1222
public static final Field PERMILLE = new Field("per mille");
1223
1224
/**
1225
* Constant identifying the currency field.
1226
*/
1227
public static final Field CURRENCY = new Field("currency");
1228
1229
/**
1230
* Constant identifying the exponent sign field.
1231
*/
1232
public static final Field EXPONENT_SIGN = new Field("exponent sign");
1233
}
1234
}
1235
1236