-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDecimalFormat.java
More file actions
2307 lines (1999 loc) · 69.8 KB
/
Copy pathDecimalFormat.java
File metadata and controls
2307 lines (1999 loc) · 69.8 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
/* DecimalFormat.java -- Formats and parses numbers
Copyright (C) 1999, 2000, 2001, 2003, 2004, 2005, 2012 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath 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 for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
/*
* This class contains few bits from ICU4J (http://icu.sourceforge.net/),
* Copyright by IBM and others and distributed under the
* distributed under MIT/X.
*/
package java.text;
import gnu.java.lang.CPStringBuilder;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Locale;
/*
* This note is here for historical reasons and because I had not the courage
* to remove it :)
*
* @author Tom Tromey (tromey@cygnus.com)
* @author Andrew John Hughes (gnu_andrew@member.fsf.org)
* @date March 4, 1999
*
* Written using "Java Class Libraries", 2nd edition, plus online
* API docs for JDK 1.2 from http://www.javasoft.com.
* Status: Believed complete and correct to 1.2.
* Note however that the docs are very unclear about how format parsing
* should work. No doubt there are problems here.
*/
/**
* This class is a concrete implementation of NumberFormat used to format
* decimal numbers. The class can format numbers given a specific locale.
* Generally, to get an instance of DecimalFormat you should call the factory
* methods in the <code>NumberFormat</code> base class.
*
* @author Mario Torre (neugens@limasoftware.net)
* @author Tom Tromey (tromey@cygnus.com)
* @author Andrew John Hughes (gnu_andrew@member.fsf.org)
*/
public class DecimalFormat extends NumberFormat
{
/** serialVersionUID for serializartion. */
private static final long serialVersionUID = 864413376551465018L;
/** Defines the default number of digits allowed while formatting integers. */
private static final int DEFAULT_INTEGER_DIGITS = 309;
/**
* Defines the default number of digits allowed while formatting
* fractions.
*/
private static final int DEFAULT_FRACTION_DIGITS = 340;
/**
* Locale-independent pattern symbols.
*/
// Happen to be the same as the US symbols.
private static final DecimalFormatSymbols nonLocalizedSymbols
= new DecimalFormatSymbols (Locale.US);
/**
* Defines if parse should return a BigDecimal or not.
*/
private boolean parseBigDecimal;
/**
* Defines if we have to use the monetary decimal separator or
* the decimal separator while formatting numbers.
*/
private boolean useCurrencySeparator;
/** Defines if the decimal separator is always shown or not. */
private boolean decimalSeparatorAlwaysShown;
/**
* Defines if the decimal separator has to be shown.
*
* This is different then <code>decimalSeparatorAlwaysShown</code>,
* as it defines if the format string contains a decimal separator or no.
*/
private boolean showDecimalSeparator;
/**
* This field is used to determine if the grouping
* separator is included in the format string or not.
* This is only needed to match the behaviour of the RI.
*/
private boolean groupingSeparatorInPattern;
/** Defines the size of grouping groups when grouping is used. */
private byte groupingSize;
/**
* This is an internal parameter used to keep track of the number
* of digits the form the exponent, when exponential notation is used.
* It is used with <code>exponentRound</code>
*/
private byte minExponentDigits;
/** This field is used to set the exponent in the engineering notation. */
private int exponentRound;
/** Multiplier used in percent style formats. */
private int multiplier;
/** Multiplier used in percent style formats. */
private int negativePatternMultiplier;
/** The negative prefix. */
private String negativePrefix;
/** The negative suffix. */
private String negativeSuffix;
/** The positive prefix. */
private String positivePrefix;
/** The positive suffix. */
private String positiveSuffix;
/** Decimal Format Symbols for the given locale. */
private DecimalFormatSymbols symbols;
/** Determine if we have to use exponential notation or not. */
private boolean useExponentialNotation;
/**
* Defines the maximum number of integer digits to show when we use
* the exponential notation.
*/
private int maxIntegerDigitsExponent;
/** Defines if the format string has a negative prefix or not. */
private boolean hasNegativePrefix;
/** Defines if the format string has a fractional pattern or not. */
private boolean hasFractionalPattern;
/** Stores a list of attributes for use by formatToCharacterIterator. */
private ArrayList<FieldPosition> attributes = new ArrayList<FieldPosition>();
/**
* Constructs a <code>DecimalFormat</code> which uses the default
* pattern and symbols.
*/
public DecimalFormat()
{
this ("#,##0.###");
}
/**
* Constructs a <code>DecimalFormat</code> which uses the given
* pattern and the default symbols for formatting and parsing.
*
* @param pattern the non-localized pattern to use.
* @throws NullPointerException if any argument is null.
* @throws IllegalArgumentException if the pattern is invalid.
*/
public DecimalFormat(String pattern)
{
this (pattern, new DecimalFormatSymbols());
}
/**
* Constructs a <code>DecimalFormat</code> using the given pattern
* and formatting symbols. This construction method is used to give
* complete control over the formatting process.
*
* @param pattern the non-localized pattern to use.
* @param symbols the set of symbols used for parsing and formatting.
* @throws NullPointerException if any argument is null.
* @throws IllegalArgumentException if the pattern is invalid.
*/
public DecimalFormat(String pattern, DecimalFormatSymbols symbols)
{
this.symbols = (DecimalFormatSymbols) symbols.clone();
applyPatternWithSymbols(pattern, nonLocalizedSymbols);
}
/**
* Apply the given localized patern to the current DecimalFormat object.
*
* @param pattern The localized pattern to apply.
* @throws IllegalArgumentException if the given pattern is invalid.
* @throws NullPointerException if the input pattern is null.
*/
public void applyLocalizedPattern (String pattern)
{
applyPatternWithSymbols(pattern, this.symbols);
}
/**
* Apply the given localized pattern to the current DecimalFormat object.
*
* @param pattern The localized pattern to apply.
* @throws IllegalArgumentException if the given pattern is invalid.
* @throws NullPointerException if the input pattern is null.
*/
public void applyPattern(String pattern)
{
applyPatternWithSymbols(pattern, nonLocalizedSymbols);
}
public Object clone()
{
DecimalFormat c = (DecimalFormat) super.clone();
c.symbols = (DecimalFormatSymbols) symbols.clone();
return c;
}
/**
* Tests this instance for equality with an arbitrary object. This method
* returns <code>true</code> if:
* <ul>
* <li><code>obj</code> is not <code>null</code>;</li>
* <li><code>obj</code> is an instance of <code>DecimalFormat</code>;</li>
* <li>this instance and <code>obj</code> have the same attributes;</li>
* </ul>
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj)
{
if (! (obj instanceof DecimalFormat))
return false;
DecimalFormat dup = (DecimalFormat) obj;
return (decimalSeparatorAlwaysShown == dup.decimalSeparatorAlwaysShown
&& groupingUsed == dup.groupingUsed
&& groupingSeparatorInPattern == dup.groupingSeparatorInPattern
&& groupingSize == dup.groupingSize
&& multiplier == dup.multiplier
&& useExponentialNotation == dup.useExponentialNotation
&& minExponentDigits == dup.minExponentDigits
&& minimumIntegerDigits == dup.minimumIntegerDigits
&& maximumIntegerDigits == dup.maximumIntegerDigits
&& minimumFractionDigits == dup.minimumFractionDigits
&& maximumFractionDigits == dup.maximumFractionDigits
&& parseBigDecimal == dup.parseBigDecimal
&& useCurrencySeparator == dup.useCurrencySeparator
&& showDecimalSeparator == dup.showDecimalSeparator
&& exponentRound == dup.exponentRound
&& negativePatternMultiplier == dup.negativePatternMultiplier
&& maxIntegerDigitsExponent == dup.maxIntegerDigitsExponent
// XXX: causes equivalent patterns to fail
// && hasNegativePrefix == dup.hasNegativePrefix
&& equals(negativePrefix, dup.negativePrefix)
&& equals(negativeSuffix, dup.negativeSuffix)
&& equals(positivePrefix, dup.positivePrefix)
&& equals(positiveSuffix, dup.positiveSuffix)
&& symbols.equals(dup.symbols));
}
/**
* Returns a hash code for this object.
*
* @return A hash code.
*/
public int hashCode()
{
return toPattern().hashCode();
}
/**
* Produce a formatted {@link String} representation of this object.
* The passed object must be of type number.
*
* @param obj The {@link Number} to format.
* @param sbuf The destination String; text will be appended to this String.
* @param pos If used on input can be used to define an alignment
* field. If used on output defines the offsets of the alignment field.
* @return The String representation of this long.
*/
public final StringBuffer format(Object obj, StringBuffer sbuf, FieldPosition pos)
{
return format(obj, sbuf, pos, false);
}
private StringBuffer format(Object obj, StringBuffer sbuf, FieldPosition pos,
boolean addAttrs)
{
if (obj instanceof BigInteger)
{
BigDecimal decimal = new BigDecimal((BigInteger) obj);
formatInternal(decimal, true, sbuf, pos, addAttrs);
return sbuf;
}
else if (obj instanceof BigDecimal)
{
formatInternal((BigDecimal) obj, false, sbuf, pos, addAttrs);
return sbuf;
}
else if (obj instanceof Number)
{
return format(((Number) obj).doubleValue(), sbuf, pos, addAttrs);
}
throw new IllegalArgumentException("Cannot format given Object as a Number");
}
/**
* Produce a formatted {@link String} representation of this double.
*
* @param number The double to format.
* @param dest The destination String; text will be appended to this String.
* @param fieldPos If used on input can be used to define an alignment
* field. If used on output defines the offsets of the alignment field.
* @return The String representation of this long.
* @throws NullPointerException if <code>dest</code> or fieldPos are null
*/
public StringBuffer format(double number, StringBuffer dest,
FieldPosition fieldPos)
{
return format(number, dest, fieldPos, false);
}
private StringBuffer format(double number, StringBuffer dest,
FieldPosition fieldPos, boolean addAttrs)
{
// special cases for double: NaN and negative or positive infinity
if (Double.isNaN(number))
{
// 1. NaN
String nan = symbols.getNaN();
dest.append(nan);
// update field position if required
if ((fieldPos.getField() == INTEGER_FIELD ||
fieldPos.getFieldAttribute() == NumberFormat.Field.INTEGER))
{
int index = dest.length();
fieldPos.setBeginIndex(index - nan.length());
fieldPos.setEndIndex(index);
}
}
else if (Double.isInfinite(number))
{
// 2. Infinity
if (number < 0)
dest.append(this.negativePrefix);
else
dest.append(this.positivePrefix);
dest.append(symbols.getInfinity());
if (number < 0)
dest.append(this.negativeSuffix);
else
dest.append(this.positiveSuffix);
if ((fieldPos.getField() == INTEGER_FIELD ||
fieldPos.getFieldAttribute() == NumberFormat.Field.INTEGER))
{
fieldPos.setBeginIndex(dest.length());
fieldPos.setEndIndex(0);
}
}
else
{
// get the number as a BigDecimal
BigDecimal bigDecimal = new BigDecimal(String.valueOf(number));
formatInternal(bigDecimal, false, dest, fieldPos, addAttrs);
}
return dest;
}
/**
* Produce a formatted {@link String} representation of this long.
*
* @param number The long to format.
* @param dest The destination String; text will be appended to this String.
* @param fieldPos If used on input can be used to define an alignment
* field. If used on output defines the offsets of the alignment field.
* @return The String representation of this long.
*/
public StringBuffer format(long number, StringBuffer dest,
FieldPosition fieldPos)
{
return format(number, dest, fieldPos, false);
}
private StringBuffer format(long number, StringBuffer dest,
FieldPosition fieldPos, boolean addAttrs)
{
BigDecimal bigDecimal = new BigDecimal(String.valueOf(number));
formatInternal(bigDecimal, true, dest, fieldPos, addAttrs);
return dest;
}
/**
* Return an <code>AttributedCharacterIterator</code> as a result of
* the formatting of the passed {@link Object}.
*
* @return An {@link AttributedCharacterIterator}.
* @throws NullPointerException if value is <code>null</code>.
* @throws IllegalArgumentException if value is not an instance of
* {@link Number}.
*/
public AttributedCharacterIterator formatToCharacterIterator(Object value)
{
/*
* This method implementation derives directly from the
* ICU4J (http://icu.sourceforge.net/) library, distributed under MIT/X.
*/
if (value == null)
throw new NullPointerException("Passed Object is null");
if (!(value instanceof Number)) throw new
IllegalArgumentException("Cannot format given Object as a Number");
StringBuffer text = new StringBuffer();
format(value, text, new FieldPosition(0), true);
AttributedString as = new AttributedString(text.toString());
// add NumberFormat field attributes to the AttributedString
for (int i = 0; i < attributes.size(); i++)
{
FieldPosition pos = attributes.get(i);
Format.Field attribute = pos.getFieldAttribute();
as.addAttribute(attribute, attribute, pos.getBeginIndex(),
pos.getEndIndex());
}
attributes.clear();
// return the CharacterIterator from AttributedString
return as.getIterator();
}
/**
* Returns the currency corresponding to the currency symbol stored
* in the instance of <code>DecimalFormatSymbols</code> used by this
* <code>DecimalFormat</code>.
*
* @return A new instance of <code>Currency</code> if
* the currency code matches a known one, null otherwise.
*/
public Currency getCurrency()
{
return symbols.getCurrency();
}
/**
* Returns a copy of the symbols used by this instance.
*
* @return A copy of the symbols.
*/
public DecimalFormatSymbols getDecimalFormatSymbols()
{
return (DecimalFormatSymbols) symbols.clone();
}
/**
* Gets the interval used between a grouping separator and the next.
* For example, a grouping size of 3 means that the number 1234 is
* formatted as 1,234.
*
* The actual character used as grouping separator depends on the
* locale and is defined by {@link DecimalFormatSymbols#getDecimalSeparator()}
*
* @return The interval used between a grouping separator and the next.
*/
public int getGroupingSize()
{
return groupingSize;
}
/**
* Gets the multiplier used in percent and similar formats.
*
* @return The multiplier used in percent and similar formats.
*/
public int getMultiplier()
{
return multiplier;
}
/**
* Gets the negative prefix.
*
* @return The negative prefix.
*/
public String getNegativePrefix()
{
return negativePrefix;
}
/**
* Gets the negative suffix.
*
* @return The negative suffix.
*/
public String getNegativeSuffix()
{
return negativeSuffix;
}
/**
* Gets the positive prefix.
*
* @return The positive prefix.
*/
public String getPositivePrefix()
{
return positivePrefix;
}
/**
* Gets the positive suffix.
*
* @return The positive suffix.
*/
public String getPositiveSuffix()
{
return positiveSuffix;
}
public boolean isDecimalSeparatorAlwaysShown()
{
return decimalSeparatorAlwaysShown;
}
/**
* Define if <code>parse(java.lang.String, java.text.ParsePosition)</code>
* should return a {@link BigDecimal} or not.
*
* @param newValue
*/
public void setParseBigDecimal(boolean newValue)
{
this.parseBigDecimal = newValue;
}
/**
* Returns <code>true</code> if
* <code>parse(java.lang.String, java.text.ParsePosition)</code> returns
* a <code>BigDecimal</code>, <code>false</code> otherwise.
* The default return value for this method is <code>false</code>.
*
* @return <code>true</code> if the parse method returns a {@link BigDecimal},
* <code>false</code> otherwise.
* @since 1.5
* @see #setParseBigDecimal(boolean)
*/
public boolean isParseBigDecimal()
{
return this.parseBigDecimal;
}
/**
* This method parses the specified string into a <code>Number</code>.
*
* The parsing starts at <code>pos</code>, which is updated as the parser
* consume characters in the passed string.
* On error, the <code>Position</code> object index is not updated, while
* error position is set appropriately, an <code>null</code> is returned.
*
* @param str The string to parse.
* @param pos The desired <code>ParsePosition</code>.
*
* @return The parsed <code>Number</code>
*/
public Number parse(String str, ParsePosition pos)
{
// a special values before anything else
// NaN
if (str.contains(this.symbols.getNaN()))
return Double.valueOf(Double.NaN);
// this will be our final number
CPStringBuilder number = new CPStringBuilder();
// special character
char minus = symbols.getMinusSign();
// starting parsing position
int start = pos.getIndex();
// validate the string, it have to be in the
// same form as the format string or parsing will fail
String _negativePrefix = (this.negativePrefix.compareTo("") == 0
? minus + positivePrefix
: this.negativePrefix);
// we check both prefixes, because one might be empty.
// We want to pick the longest prefix that matches.
int positiveLen = positivePrefix.length();
int negativeLen = _negativePrefix.length();
boolean isNegative = str.startsWith(_negativePrefix);
boolean isPositive = str.startsWith(positivePrefix);
if (isPositive && isNegative)
{
// By checking this way, we preserve ambiguity in the case
// where the negative format differs only in suffix.
if (negativeLen > positiveLen)
{
start += _negativePrefix.length();
isNegative = true;
}
else
{
start += positivePrefix.length();
isPositive = true;
if (negativeLen < positiveLen)
isNegative = false;
}
}
else if (isNegative)
{
start += _negativePrefix.length();
isPositive = false;
}
else if (isPositive)
{
start += positivePrefix.length();
isNegative = false;
}
else
{
pos.setErrorIndex(start);
return null;
}
// other special characters used by the parser
char decimalSeparator = symbols.getDecimalSeparator();
char zero = symbols.getZeroDigit();
char exponent = symbols.getExponential();
// stop parsing position in the string
int stop = start + this.maximumIntegerDigits + maximumFractionDigits + 2;
if (useExponentialNotation)
stop += minExponentDigits + 1;
boolean inExponent = false;
// correct the size of the end parsing flag
int len = str.length();
if (len < stop) stop = len;
char groupingSeparator = symbols.getGroupingSeparator();
int i = start;
while (i < stop)
{
char ch = str.charAt(i);
i++;
if (ch >= zero && ch <= (zero + 9))
{
number.append(ch);
}
else if (this.parseIntegerOnly)
{
i--;
break;
}
else if (ch == decimalSeparator)
{
number.append('.');
}
else if (ch == exponent)
{
number.append(ch);
inExponent = !inExponent;
}
else if ((ch == '+' || ch == '-' || ch == minus))
{
if (inExponent)
number.append(ch);
else
{
i--;
break;
}
}
else
{
if (!groupingUsed || ch != groupingSeparator)
{
i--;
break;
}
}
}
// 2nd special case: infinity
// XXX: need to be tested
if (str.contains(symbols.getInfinity()))
{
int inf = str.indexOf(symbols.getInfinity());
pos.setIndex(inf);
// FIXME: ouch, this is really ugly and lazy code...
if (this.parseBigDecimal)
{
if (isNegative)
return BigDecimal.valueOf(Double.NEGATIVE_INFINITY);
return BigDecimal.valueOf(Double.POSITIVE_INFINITY);
}
if (isNegative)
return Double.valueOf(Double.NEGATIVE_INFINITY);
return Double.valueOf(Double.POSITIVE_INFINITY);
}
// no number...
if (i == start || number.length() == 0)
{
pos.setErrorIndex(i);
return null;
}
// now we have to check the suffix, done here after number parsing
// or the index will not be updated correctly...
boolean hasNegativeSuffix = str.endsWith(this.negativeSuffix);
boolean hasPositiveSuffix = str.endsWith(this.positiveSuffix);
boolean positiveEqualsNegative = negativeSuffix.equals(positiveSuffix);
positiveLen = positiveSuffix.length();
negativeLen = negativeSuffix.length();
if (isNegative && !hasNegativeSuffix)
{
pos.setErrorIndex(i);
return null;
}
else if (hasNegativeSuffix &&
!positiveEqualsNegative &&
(negativeLen > positiveLen))
{
isNegative = true;
}
else if (!hasPositiveSuffix)
{
pos.setErrorIndex(i);
return null;
}
if (isNegative) number.insert(0, '-');
pos.setIndex(i);
// now we handle the return type
BigDecimal bigDecimal = new BigDecimal(number.toString());
if (this.parseBigDecimal)
return bigDecimal;
// want integer?
if (this.parseIntegerOnly)
return Long.valueOf(bigDecimal.longValue());
// 3th special case -0.0
if (isNegative && (bigDecimal.compareTo(BigDecimal.ZERO) == 0))
return Double.valueOf(-0.0);
try
{
BigDecimal integer
= bigDecimal.setScale(0, BigDecimal.ROUND_UNNECESSARY);
return Long.valueOf(integer.longValue());
}
catch (ArithmeticException e)
{
return Double.valueOf(bigDecimal.doubleValue());
}
}
/**
* Sets the <code>Currency</code> on the
* <code>DecimalFormatSymbols</code> used, which also sets the
* currency symbols on those symbols.
*
* @param currency The new <code>Currency</code> on the
* <code>DecimalFormatSymbols</code>.
*/
public void setCurrency(Currency currency)
{
Currency current = symbols.getCurrency();
if (current != currency)
{
String oldSymbol = symbols.getCurrencySymbol();
int len = oldSymbol.length();
symbols.setCurrency(currency);
String newSymbol = symbols.getCurrencySymbol();
int posPre = positivePrefix.indexOf(oldSymbol);
if (posPre != -1)
positivePrefix = positivePrefix.substring(0, posPre) +
newSymbol + positivePrefix.substring(posPre+len);
int negPre = negativePrefix.indexOf(oldSymbol);
if (negPre != -1)
negativePrefix = negativePrefix.substring(0, negPre) +
newSymbol + negativePrefix.substring(negPre+len);
int posSuf = positiveSuffix.indexOf(oldSymbol);
if (posSuf != -1)
positiveSuffix = positiveSuffix.substring(0, posSuf) +
newSymbol + positiveSuffix.substring(posSuf+len);
int negSuf = negativeSuffix.indexOf(oldSymbol);
if (negSuf != -1)
negativeSuffix = negativeSuffix.substring(0, negSuf) +
newSymbol + negativeSuffix.substring(negSuf+len);
}
}
/**
* Sets the symbols used by this instance. This method makes a copy of
* the supplied symbols.
*
* @param newSymbols the symbols (<code>null</code> not permitted).
*/
public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols)
{
symbols = (DecimalFormatSymbols) newSymbols.clone();
}
/**
* Define if the decimal separator should be always visible or only
* visible when needed. This method as effect only on integer values.
* Pass <code>true</code> if you want the decimal separator to be
* always shown, <code>false</code> otherwise.
*
* @param newValue true</code> if you want the decimal separator to be
* always shown, <code>false</code> otherwise.
*/
public void setDecimalSeparatorAlwaysShown(boolean newValue)
{
decimalSeparatorAlwaysShown = newValue;
}
/**
* Sets the number of digits used to group portions of the integer part of
* the number. For example, the number <code>123456</code>, with a grouping
* size of 3, is rendered <code>123,456</code>.
*
* @param groupSize The number of digits used while grouping portions
* of the integer part of a number.
*/
public void setGroupingSize(int groupSize)
{
groupingSize = (byte) groupSize;
}
/**
* Sets the maximum number of digits allowed in the integer
* portion of a number to the specified value.
* The new value will be the choosen as the minimum between
* <code>newvalue</code> and 309. Any value below zero will be
* replaced by zero.
*
* @param newValue The new maximum integer digits value.
*/
public void setMaximumIntegerDigits(int newValue)
{
newValue = (newValue > 0) ? newValue : 0;
super.setMaximumIntegerDigits(Math.min(newValue, DEFAULT_INTEGER_DIGITS));
}
/**
* Sets the minimum number of digits allowed in the integer
* portion of a number to the specified value.
* The new value will be the choosen as the minimum between
* <code>newvalue</code> and 309. Any value below zero will be
* replaced by zero.
*
* @param newValue The new minimum integer digits value.
*/
public void setMinimumIntegerDigits(int newValue)
{
newValue = (newValue > 0) ? newValue : 0;
super.setMinimumIntegerDigits(Math.min(newValue, DEFAULT_INTEGER_DIGITS));
}
/**
* Sets the maximum number of digits allowed in the fraction
* portion of a number to the specified value.
* The new value will be the choosen as the minimum between
* <code>newvalue</code> and 309. Any value below zero will be
* replaced by zero.
*
* @param newValue The new maximum fraction digits value.
*/
public void setMaximumFractionDigits(int newValue)
{
newValue = (newValue > 0) ? newValue : 0;
super.setMaximumFractionDigits(Math.min(newValue, DEFAULT_FRACTION_DIGITS));
}
/**
* Sets the minimum number of digits allowed in the fraction
* portion of a number to the specified value.
* The new value will be the choosen as the minimum between
* <code>newvalue</code> and 309. Any value below zero will be
* replaced by zero.
*
* @param newValue The new minimum fraction digits value.
*/
public void setMinimumFractionDigits(int newValue)
{
newValue = (newValue > 0) ? newValue : 0;
super.setMinimumFractionDigits(Math.min(newValue, DEFAULT_FRACTION_DIGITS));
}
/**
* Sets the multiplier for use in percent and similar formats.
* For example, for percent set the multiplier to 100, for permille, set the
* miltiplier to 1000.
*
* @param newValue the new value for multiplier.
*/
public void setMultiplier(int newValue)
{
multiplier = newValue;
}
/**
* Sets the negative prefix.
*
* @param newValue The new negative prefix.
*/
public void setNegativePrefix(String newValue)
{
negativePrefix = newValue;
}
/**
* Sets the negative suffix.
*
* @param newValue The new negative suffix.
*/
public void setNegativeSuffix(String newValue)
{
negativeSuffix = newValue;
}
/**
* Sets the positive prefix.
*
* @param newValue The new positive prefix.
*/
public void setPositivePrefix(String newValue)
{
positivePrefix = newValue;
}
/**
* Sets the new positive suffix.
*
* @param newValue The new positive suffix.
*/
public void setPositiveSuffix(String newValue)
{
positiveSuffix = newValue;
}