forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BigDecimal.java
5847 lines (5463 loc) · 242 KB
/
BigDecimal.java
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, 2017, 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.
*/
/*
* Portions Copyright IBM Corporation, 2001. All Rights Reserved.
*/
package java.math;
import java.util.Arrays;
import static java.math.BigInteger.LONG_MASK;
/**
* Immutable, arbitrary-precision signed decimal numbers. A
* {@code BigDecimal} consists of an arbitrary precision integer
* <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero
* or positive, the scale is the number of digits to the right of the
* decimal point. If negative, the unscaled value of the number is
* multiplied by ten to the power of the negation of the scale. The
* value of the number represented by the {@code BigDecimal} is
* therefore <code>(unscaledValue × 10<sup>-scale</sup>)</code>.
*
* <p>The {@code BigDecimal} class provides operations for
* arithmetic, scale manipulation, rounding, comparison, hashing, and
* format conversion. The {@link #toString} method provides a
* canonical representation of a {@code BigDecimal}.
*
* <p>The {@code BigDecimal} class gives its user complete control
* over rounding behavior. If no rounding mode is specified and the
* exact result cannot be represented, an exception is thrown;
* otherwise, calculations can be carried out to a chosen precision
* and rounding mode by supplying an appropriate {@link MathContext}
* object to the operation. In either case, eight <em>rounding
* modes</em> are provided for the control of rounding. Using the
* integer fields in this class (such as {@link #ROUND_HALF_UP}) to
* represent rounding mode is deprecated; the enumeration values
* of the {@code RoundingMode} {@code enum}, (such as {@link
* RoundingMode#HALF_UP}) should be used instead.
*
* <p>When a {@code MathContext} object is supplied with a precision
* setting of 0 (for example, {@link MathContext#UNLIMITED}),
* arithmetic operations are exact, as are the arithmetic methods
* which take no {@code MathContext} object. (This is the only
* behavior that was supported in releases prior to 5.) As a
* corollary of computing the exact result, the rounding mode setting
* of a {@code MathContext} object with a precision setting of 0 is
* not used and thus irrelevant. In the case of divide, the exact
* quotient could have an infinitely long decimal expansion; for
* example, 1 divided by 3. If the quotient has a nonterminating
* decimal expansion and the operation is specified to return an exact
* result, an {@code ArithmeticException} is thrown. Otherwise, the
* exact result of the division is returned, as done for other
* operations.
*
* <p>When the precision setting is not 0, the rules of
* {@code BigDecimal} arithmetic are broadly compatible with selected
* modes of operation of the arithmetic defined in ANSI X3.274-1996
* and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those
* standards, {@code BigDecimal} includes many rounding modes, which
* were mandatory for division in {@code BigDecimal} releases prior
* to 5. Any conflicts between these ANSI standards and the
* {@code BigDecimal} specification are resolved in favor of
* {@code BigDecimal}.
*
* <p>Since the same numerical value can have different
* representations (with different scales), the rules of arithmetic
* and rounding must specify both the numerical result and the scale
* used in the result's representation.
*
*
* <p>In general the rounding modes and precision setting determine
* how operations return results with a limited number of digits when
* the exact result has more digits (perhaps infinitely many in the
* case of division and square root) than the number of digits returned.
*
* First, the
* total number of digits to return is specified by the
* {@code MathContext}'s {@code precision} setting; this determines
* the result's <i>precision</i>. The digit count starts from the
* leftmost nonzero digit of the exact result. The rounding mode
* determines how any discarded trailing digits affect the returned
* result.
*
* <p>For all arithmetic operators , the operation is carried out as
* though an exact intermediate result were first calculated and then
* rounded to the number of digits specified by the precision setting
* (if necessary), using the selected rounding mode. If the exact
* result is not returned, some digit positions of the exact result
* are discarded. When rounding increases the magnitude of the
* returned result, it is possible for a new digit position to be
* created by a carry propagating to a leading {@literal "9"} digit.
* For example, rounding the value 999.9 to three digits rounding up
* would be numerically equal to one thousand, represented as
* 100×10<sup>1</sup>. In such cases, the new {@literal "1"} is
* the leading digit position of the returned result.
*
* <p>Besides a logical exact result, each arithmetic operation has a
* preferred scale for representing a result. The preferred
* scale for each operation is listed in the table below.
*
* <table class="striped" style="text-align:left">
* <caption>Preferred Scales for Results of Arithmetic Operations
* </caption>
* <thead>
* <tr><th scope="col">Operation</th><th scope="col">Preferred Scale of Result</th></tr>
* </thead>
* <tbody>
* <tr><th scope="row">Add</th><td>max(addend.scale(), augend.scale())</td>
* <tr><th scope="row">Subtract</th><td>max(minuend.scale(), subtrahend.scale())</td>
* <tr><th scope="row">Multiply</th><td>multiplier.scale() + multiplicand.scale()</td>
* <tr><th scope="row">Divide</th><td>dividend.scale() - divisor.scale()</td>
* <tr><th scope="row">Square root</th><td>radicand.scale()/2</td>
* </tbody>
* </table>
*
* These scales are the ones used by the methods which return exact
* arithmetic results; except that an exact divide may have to use a
* larger scale since the exact result may have more digits. For
* example, {@code 1/32} is {@code 0.03125}.
*
* <p>Before rounding, the scale of the logical exact intermediate
* result is the preferred scale for that operation. If the exact
* numerical result cannot be represented in {@code precision}
* digits, rounding selects the set of digits to return and the scale
* of the result is reduced from the scale of the intermediate result
* to the least scale which can represent the {@code precision}
* digits actually returned. If the exact result can be represented
* with at most {@code precision} digits, the representation
* of the result with the scale closest to the preferred scale is
* returned. In particular, an exactly representable quotient may be
* represented in fewer than {@code precision} digits by removing
* trailing zeros and decreasing the scale. For example, rounding to
* three digits using the {@linkplain RoundingMode#FLOOR floor}
* rounding mode, <br>
*
* {@code 19/100 = 0.19 // integer=19, scale=2} <br>
*
* but<br>
*
* {@code 21/110 = 0.190 // integer=190, scale=3} <br>
*
* <p>Note that for add, subtract, and multiply, the reduction in
* scale will equal the number of digit positions of the exact result
* which are discarded. If the rounding causes a carry propagation to
* create a new high-order digit position, an additional digit of the
* result is discarded than when no new digit position is created.
*
* <p>Other methods may have slightly different rounding semantics.
* For example, the result of the {@code pow} method using the
* {@linkplain #pow(int, MathContext) specified algorithm} can
* occasionally differ from the rounded mathematical result by more
* than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.
*
* <p>Two types of operations are provided for manipulating the scale
* of a {@code BigDecimal}: scaling/rounding operations and decimal
* point motion operations. Scaling/rounding operations ({@link
* #setScale setScale} and {@link #round round}) return a
* {@code BigDecimal} whose value is approximately (or exactly) equal
* to that of the operand, but whose scale or precision is the
* specified value; that is, they increase or decrease the precision
* of the stored number with minimal effect on its value. Decimal
* point motion operations ({@link #movePointLeft movePointLeft} and
* {@link #movePointRight movePointRight}) return a
* {@code BigDecimal} created from the operand by moving the decimal
* point a specified distance in the specified direction.
*
* <p>For the sake of brevity and clarity, pseudo-code is used
* throughout the descriptions of {@code BigDecimal} methods. The
* pseudo-code expression {@code (i + j)} is shorthand for "a
* {@code BigDecimal} whose value is that of the {@code BigDecimal}
* {@code i} added to that of the {@code BigDecimal}
* {@code j}." The pseudo-code expression {@code (i == j)} is
* shorthand for "{@code true} if and only if the
* {@code BigDecimal} {@code i} represents the same value as the
* {@code BigDecimal} {@code j}." Other pseudo-code expressions
* are interpreted similarly. Square brackets are used to represent
* the particular {@code BigInteger} and scale pair defining a
* {@code BigDecimal} value; for example [19, 2] is the
* {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
*
*
* <p>All methods and constructors for this class throw
* {@code NullPointerException} when passed a {@code null} object
* reference for any input parameter.
*
* @apiNote Care should be exercised if {@code BigDecimal} objects
* are used as keys in a {@link java.util.SortedMap SortedMap} or
* elements in a {@link java.util.SortedSet SortedSet} since
* {@code BigDecimal}'s <i>natural ordering</i> is <em>inconsistent
* with equals</em>. See {@link Comparable}, {@link
* java.util.SortedMap} or {@link java.util.SortedSet} for more
* information.
*
* @see BigInteger
* @see MathContext
* @see RoundingMode
* @see java.util.SortedMap
* @see java.util.SortedSet
* @author Josh Bloch
* @author Mike Cowlishaw
* @author Joseph D. Darcy
* @author Sergey V. Kuksenko
* @since 1.1
*/
/*
* 高精度数值
*
* 注:该对象本身是不可变的,类似String,在运算之后会产生一个新对象
*/
public class BigDecimal extends Number implements Comparable<BigDecimal> {
/**
* The unscaled value of this BigDecimal, as returned by {@link
* #unscaledValue}.
*
* @serial
* @see #unscaledValue
*/
private final BigInteger intVal;
/**
* The scale of this BigDecimal, as returned by {@link #scale}.
*
* @serial
* @see #scale
*/
private final int scale; // Note: this may have any value, so calculations must be done in longs
/**
* The number of decimal digits in this BigDecimal, or 0 if the
* number of digits are not known (lookaside information). If
* nonzero, the value is guaranteed correct. Use the precision()
* method to obtain and set the value if it might be 0. This
* field is mutable until set nonzero.
*
* @since 1.5
*/
private transient int precision;
/**
* Used to store the canonical string representation, if computed.
*/
private transient String stringCache;
/**
* Sentinel value for {@link #intCompact} indicating the
* significand information is only available from {@code intVal}.
*/
static final long INFLATED = Long.MIN_VALUE;
private static final BigInteger INFLATED_BIGINT = BigInteger.valueOf(INFLATED);
/**
* If the absolute value of the significand of this BigDecimal is
* less than or equal to {@code Long.MAX_VALUE}, the value can be
* compactly stored in this field and used in computations.
*/
private final transient long intCompact;
// All 18-digit base ten strings fit into a long; not all 19-digit strings will
private static final int MAX_COMPACT_DIGITS = 18;
private static final ThreadLocal<StringBuilderHelper> threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {
@Override
protected StringBuilderHelper initialValue() {
return new StringBuilderHelper();
}
};
// Cache of common small BigDecimal values.
private static final BigDecimal ZERO_THROUGH_TEN[] = {
new BigDecimal(BigInteger.ZERO, 0, 0, 1),
new BigDecimal(BigInteger.ONE, 1, 0, 1),
new BigDecimal(BigInteger.TWO, 2, 0, 1),
new BigDecimal(BigInteger.valueOf(3), 3, 0, 1),
new BigDecimal(BigInteger.valueOf(4), 4, 0, 1),
new BigDecimal(BigInteger.valueOf(5), 5, 0, 1),
new BigDecimal(BigInteger.valueOf(6), 6, 0, 1),
new BigDecimal(BigInteger.valueOf(7), 7, 0, 1),
new BigDecimal(BigInteger.valueOf(8), 8, 0, 1),
new BigDecimal(BigInteger.valueOf(9), 9, 0, 1),
new BigDecimal(BigInteger.TEN, 10, 0, 2),
};
// Cache of zero scaled by 0 - 15
private static final BigDecimal[] ZERO_SCALED_BY = {
ZERO_THROUGH_TEN[0],
new BigDecimal(BigInteger.ZERO, 0, 1, 1),
new BigDecimal(BigInteger.ZERO, 0, 2, 1),
new BigDecimal(BigInteger.ZERO, 0, 3, 1),
new BigDecimal(BigInteger.ZERO, 0, 4, 1),
new BigDecimal(BigInteger.ZERO, 0, 5, 1),
new BigDecimal(BigInteger.ZERO, 0, 6, 1),
new BigDecimal(BigInteger.ZERO, 0, 7, 1),
new BigDecimal(BigInteger.ZERO, 0, 8, 1),
new BigDecimal(BigInteger.ZERO, 0, 9, 1),
new BigDecimal(BigInteger.ZERO, 0, 10, 1),
new BigDecimal(BigInteger.ZERO, 0, 11, 1),
new BigDecimal(BigInteger.ZERO, 0, 12, 1),
new BigDecimal(BigInteger.ZERO, 0, 13, 1),
new BigDecimal(BigInteger.ZERO, 0, 14, 1),
new BigDecimal(BigInteger.ZERO, 0, 15, 1),
};
// Half of Long.MIN_VALUE & Long.MAX_VALUE.
private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2;
private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2;
// Constants
/**
* The value 0, with a scale of 0.
*
* @since 1.5
*/
public static final BigDecimal ZERO = ZERO_THROUGH_TEN[0];
/**
* The value 1, with a scale of 0.
*
* @since 1.5
*/
public static final BigDecimal ONE = ZERO_THROUGH_TEN[1];
/**
* The value 10, with a scale of 0.
*
* @since 1.5
*/
public static final BigDecimal TEN = ZERO_THROUGH_TEN[10];
/**
* The value 0.1, with a scale of 1.
*/
private static final BigDecimal ONE_TENTH = valueOf(1L, 1);
/**
* The value 0.5, with a scale of 1.
*/
private static final BigDecimal ONE_HALF = valueOf(5L, 1);
private static final long[] LONG_TEN_POWERS_TABLE = {
1, // 0 / 10^0
10, // 1 / 10^1
100, // 2 / 10^2
1000, // 3 / 10^3
10000, // 4 / 10^4
100000, // 5 / 10^5
1000000, // 6 / 10^6
10000000, // 7 / 10^7
100000000, // 8 / 10^8
1000000000, // 9 / 10^9
10000000000L, // 10 / 10^10
100000000000L, // 11 / 10^11
1000000000000L, // 12 / 10^12
10000000000000L, // 13 / 10^13
100000000000000L, // 14 / 10^14
1000000000000000L, // 15 / 10^15
10000000000000000L, // 16 / 10^16
100000000000000000L, // 17 / 10^17
1000000000000000000L // 18 / 10^18
};
private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {
BigInteger.ONE,
BigInteger.valueOf(10),
BigInteger.valueOf(100),
BigInteger.valueOf(1000),
BigInteger.valueOf(10000),
BigInteger.valueOf(100000),
BigInteger.valueOf(1000000),
BigInteger.valueOf(10000000),
BigInteger.valueOf(100000000),
BigInteger.valueOf(1000000000),
BigInteger.valueOf(10000000000L),
BigInteger.valueOf(100000000000L),
BigInteger.valueOf(1000000000000L),
BigInteger.valueOf(10000000000000L),
BigInteger.valueOf(100000000000000L),
BigInteger.valueOf(1000000000000000L),
BigInteger.valueOf(10000000000000000L),
BigInteger.valueOf(100000000000000000L),
BigInteger.valueOf(1000000000000000000L)
};
private static final int BIG_TEN_POWERS_TABLE_INITLEN = BIG_TEN_POWERS_TABLE.length;
private static final int BIG_TEN_POWERS_TABLE_MAX = 16 * BIG_TEN_POWERS_TABLE_INITLEN;
private static final long THRESHOLDS_TABLE[] = {
Long.MAX_VALUE, // 0
Long.MAX_VALUE/10L, // 1
Long.MAX_VALUE/100L, // 2
Long.MAX_VALUE/1000L, // 3
Long.MAX_VALUE/10000L, // 4
Long.MAX_VALUE/100000L, // 5
Long.MAX_VALUE/1000000L, // 6
Long.MAX_VALUE/10000000L, // 7
Long.MAX_VALUE/100000000L, // 8
Long.MAX_VALUE/1000000000L, // 9
Long.MAX_VALUE/10000000000L, // 10
Long.MAX_VALUE/100000000000L, // 11
Long.MAX_VALUE/1000000000000L, // 12
Long.MAX_VALUE/10000000000000L, // 13
Long.MAX_VALUE/100000000000000L, // 14
Long.MAX_VALUE/1000000000000000L, // 15
Long.MAX_VALUE/10000000000000000L, // 16
Long.MAX_VALUE/100000000000000000L, // 17
Long.MAX_VALUE/1000000000000000000L // 18
};
/**
* Rounding mode to round away from zero. Always increments the
* digit prior to a nonzero discarded fraction. Note that this rounding
* mode never decreases the magnitude of the calculated value.
*
* @deprecated Use {@link RoundingMode#UP} instead.
*/
// 向两端舍入(负数朝左,正数朝右)
@Deprecated(since="9")
public static final int ROUND_UP = 0;
/**
* Rounding mode to round towards zero. Never increments the digit
* prior to a discarded fraction (i.e., truncates). Note that this
* rounding mode never increases the magnitude of the calculated value.
*
* @deprecated Use {@link RoundingMode#DOWN} instead.
*/
// 向0舍入(负数朝右,正数朝左)
@Deprecated(since="9")
public static final int ROUND_DOWN = 1;
/**
* Rounding mode to round towards positive infinity. If the
* {@code BigDecimal} is positive, behaves as for
* {@code ROUND_UP}; if negative, behaves as for
* {@code ROUND_DOWN}. Note that this rounding mode never
* decreases the calculated value.
*
* @deprecated Use {@link RoundingMode#CEILING} instead.
*/
// 向右舍入
@Deprecated(since="9")
public static final int ROUND_CEILING = 2;
/**
* Rounding mode to round towards negative infinity. If the
* {@code BigDecimal} is positive, behave as for
* {@code ROUND_DOWN}; if negative, behave as for
* {@code ROUND_UP}. Note that this rounding mode never
* increases the calculated value.
*
* @deprecated Use {@link RoundingMode#FLOOR} instead.
*/
// 向左舍入
@Deprecated(since="9")
public static final int ROUND_FLOOR = 3;
/**
* Rounding mode to round towards {@literal "nearest neighbor"}
* unless both neighbors are equidistant, in which case round up.
* Behaves as for {@code ROUND_UP} if the discarded fraction is
* ≥ 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note
* that this is the rounding mode that most of us were taught in
* grade school.
*
* @deprecated Use {@link RoundingMode#HALF_UP} instead.
*/
// 返回最近的整数,如果该数位于两个整数正中间,向两端舍入
@Deprecated(since="9")
public static final int ROUND_HALF_UP = 4;
/**
* Rounding mode to round towards {@literal "nearest neighbor"}
* unless both neighbors are equidistant, in which case round
* down. Behaves as for {@code ROUND_UP} if the discarded
* fraction is {@literal >} 0.5; otherwise, behaves as for
* {@code ROUND_DOWN}.
*
* @deprecated Use {@link RoundingMode#HALF_DOWN} instead.
*/
// 返回最近的整数,如果该数位于两个整数正中间,向0舍入
@Deprecated(since="9")
public static final int ROUND_HALF_DOWN = 5;
/**
* Rounding mode to round towards the {@literal "nearest neighbor"}
* unless both neighbors are equidistant, in which case, round
* towards the even neighbor. Behaves as for
* {@code ROUND_HALF_UP} if the digit to the left of the
* discarded fraction is odd; behaves as for
* {@code ROUND_HALF_DOWN} if it's even. Note that this is the
* rounding mode that minimizes cumulative error when applied
* repeatedly over a sequence of calculations.
*
* @deprecated Use {@link RoundingMode#HALF_EVEN} instead.
*/
// 返回最近的整数,如果该数位于两个整数正中间,向偶数舍入
@Deprecated(since="9")
public static final int ROUND_HALF_EVEN = 6;
/**
* Rounding mode to assert that the requested operation has an exact
* result, hence no rounding is necessary. If this rounding mode is
* specified on an operation that yields an inexact result, an
* {@code ArithmeticException} is thrown.
*
* @deprecated Use {@link RoundingMode#UNNECESSARY} instead.
*/
// 用于诊断该舍入操作的数据是否为整数,如果不是整数,抛异常
@Deprecated(since = "9")
public static final int ROUND_UNNECESSARY = 7;
private static final long[][] LONGLONG_TEN_POWERS_TABLE = {{0L, 0x8AC7230489E80000L}, //10^19
{0x5L, 0x6bc75e2d63100000L}, //10^20
{0x36L, 0x35c9adc5dea00000L}, //10^21
{0x21eL, 0x19e0c9bab2400000L}, //10^22
{0x152dL, 0x02c7e14af6800000L}, //10^23
{0xd3c2L, 0x1bcecceda1000000L}, //10^24
{0x84595L, 0x161401484a000000L}, //10^25
{0x52b7d2L, 0xdcc80cd2e4000000L}, //10^26
{0x33b2e3cL, 0x9fd0803ce8000000L}, //10^27
{0x204fce5eL, 0x3e25026110000000L}, //10^28
{0x1431e0faeL, 0x6d7217caa0000000L}, //10^29
{0xc9f2c9cd0L, 0x4674edea40000000L}, //10^30
{0x7e37be2022L, 0xc0914b2680000000L}, //10^31
{0x4ee2d6d415bL, 0x85acef8100000000L}, //10^32
{0x314dc6448d93L, 0x38c15b0a00000000L}, //10^33
{0x1ed09bead87c0L, 0x378d8e6400000000L}, //10^34
{0x13426172c74d82L, 0x2b878fe800000000L}, //10^35
{0xc097ce7bc90715L, 0xb34b9f1000000000L}, //10^36
{0x785ee10d5da46d9L, 0x00f436a000000000L}, //10^37
{0x4b3b4ca85a86c47aL, 0x098a224000000000L}, //10^38
};
/**
* Powers of 10 which can be represented exactly in {@code
* double}.
*/
private static final double DOUBLE_10_POW[] = {1.0e0, 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5, 1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10, 1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17,
1.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e22
};
/**
* Powers of 10 which can be represented exactly in {@code
* float}.
*/
private static final float FLOAT_10_POW[] = {
1.0e0f, 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
};
private static final long DIV_NUM_BASE = (1L << 32); // Number base (32 bits).
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Translates a character array representation of a
* {@code BigDecimal} into a {@code BigDecimal}, accepting the
* same sequence of characters as the {@link #BigDecimal(String)}
* constructor, while allowing a sub-array to be specified and
* with rounding according to the context settings.
*
* @param in {@code char} array that is the source of characters.
* @param offset first character in the array to inspect.
* @param len number of characters to consider.
* @param mc the context to use.
*
* @throws ArithmeticException if the result is inexact but the
* rounding mode is {@code UNNECESSARY}.
* @throws NumberFormatException if {@code in} is not a valid
* representation of a {@code BigDecimal} or the defined subarray
* is not wholly within {@code in}.
* @implNote If the sequence of characters is already available
* within a character array, using this constructor is faster than
* converting the {@code char} array to string and using the
* {@code BigDecimal(String)} constructor.
* @since 1.5
*/
/*
* ▶ 1
*
* 使用in[offset, offset+len-1]范围的字符序列构造BigDecimal,精度由mc给出。
*/
public BigDecimal(char[] in, int offset, int len, MathContext mc) {
// protect against huge length.
if(offset + len>in.length || offset<0) {
throw new NumberFormatException("Bad offset or len arguments for char[] input.");
}
// This is the primary string to BigDecimal constructor; all
// incoming strings end up here; it uses explicit (inline)
// parsing for speed and generates at most one intermediate
// (temporary) object (a char[] array) for non-compact case.
// Use locals for all fields values until completion
int prec = 0; // record precision value
int scl = 0; // record scale value
long rs = 0; // the compact value in long
BigInteger rb = null; // the inflated value in BigInteger
// use array bounds checking to handle too-long, len == 0,
// bad offset, etc.
try {
// handle the sign
boolean isneg = false; // assume positive
if(in[offset] == '-') {
isneg = true; // leading minus means negative
offset++;
len--;
} else if(in[offset] == '+') { // leading + allowed
offset++;
len--;
}
// should now be at numeric part of the significand
boolean dot = false; // true when there is a '.'
long exp = 0; // exponent
char c; // current character
boolean isCompact = (len<=MAX_COMPACT_DIGITS);
// integer significand array & idx is the index to it. The array
// is ONLY used when we can't use a compact representation.
int idx = 0;
if(isCompact) {
// First compact case, we need not to preserve the character
// and we can just compute the value in place.
for(; len>0; offset++, len--) {
c = in[offset];
if((c == '0')) { // have zero
if(prec == 0)
prec = 1;
else if(rs != 0) {
rs *= 10;
++prec;
} // else digit is a redundant leading zero
if(dot)
++scl;
} else if((c >= '1' && c<='9')) { // have digit
int digit = c - '0';
if(prec != 1 || rs != 0)
++prec; // prec unchanged if preceded by 0s
rs = rs * 10 + digit;
if(dot)
++scl;
} else if(c == '.') { // have dot
// have dot
if(dot) // two dots
throw new NumberFormatException("Character array" + " contains more than one decimal point.");
dot = true;
} else if(Character.isDigit(c)) { // slow path
int digit = Character.digit(c, 10);
if(digit == 0) {
if(prec == 0)
prec = 1;
else if(rs != 0) {
rs *= 10;
++prec;
} // else digit is a redundant leading zero
} else {
if(prec != 1 || rs != 0)
++prec; // prec unchanged if preceded by 0s
rs = rs * 10 + digit;
}
if(dot)
++scl;
} else if((c == 'e') || (c == 'E')) {
exp = parseExp(in, offset, len);
// Next test is required for backwards compatibility
if((int) exp != exp) // overflow
throw new NumberFormatException("Exponent overflow.");
break; // [saves a test]
} else {
throw new NumberFormatException("Character " + c + " is neither a decimal digit number, decimal point, nor" + " \"e\" notation exponential mark.");
}
}
if(prec == 0) // no digits found
throw new NumberFormatException("No digits found.");
// Adjust scale if exp is not zero.
if(exp != 0) { // had significant exponent
scl = adjustScale(scl, exp);
}
rs = isneg ? -rs : rs;
int mcp = mc.precision;
int drop = prec - mcp; // prec has range [1, MAX_INT], mcp has range [0, MAX_INT];
// therefore, this subtract cannot overflow
if(mcp>0 && drop>0) { // do rounding
while(drop>0) {
scl = checkScaleNonZero((long) scl - drop);
rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
prec = longDigitLength(rs);
drop = prec - mcp;
}
}
} else {
char coeff[] = new char[len];
for(; len>0; offset++, len--) {
c = in[offset];
// have digit
if((c >= '0' && c<='9') || Character.isDigit(c)) {
// First compact case, we need not to preserve the character
// and we can just compute the value in place.
if(c == '0' || Character.digit(c, 10) == 0) {
if(prec == 0) {
coeff[idx] = c;
prec = 1;
} else if(idx != 0) {
coeff[idx++] = c;
++prec;
} // else c must be a redundant leading zero
} else {
if(prec != 1 || idx != 0)
++prec; // prec unchanged if preceded by 0s
coeff[idx++] = c;
}
if(dot)
++scl;
continue;
}
// have dot
if(c == '.') {
// have dot
if(dot) // two dots
throw new NumberFormatException("Character array" + " contains more than one decimal point.");
dot = true;
continue;
}
// exponent expected
if((c != 'e') && (c != 'E'))
throw new NumberFormatException("Character array" + " is missing \"e\" notation exponential mark.");
exp = parseExp(in, offset, len);
// Next test is required for backwards compatibility
if((int) exp != exp) // overflow
throw new NumberFormatException("Exponent overflow.");
break; // [saves a test]
}
// here when no characters left
if(prec == 0) // no digits found
throw new NumberFormatException("No digits found.");
// Adjust scale if exp is not zero.
if(exp != 0) { // had significant exponent
scl = adjustScale(scl, exp);
}
// Remove leading zeros from precision (digits count)
rb = new BigInteger(coeff, isneg ? -1 : 1, prec);
rs = compactValFor(rb);
int mcp = mc.precision;
if(mcp>0 && (prec>mcp)) {
if(rs == INFLATED) {
int drop = prec - mcp;
while(drop>0) {
scl = checkScaleNonZero((long) scl - drop);
rb = divideAndRoundByTenPow(rb, drop, mc.roundingMode.oldMode);
rs = compactValFor(rb);
if(rs != INFLATED) {
prec = longDigitLength(rs);
break;
}
prec = bigDigitLength(rb);
drop = prec - mcp;
}
}
if(rs != INFLATED) {
int drop = prec - mcp;
while(drop>0) {
scl = checkScaleNonZero((long) scl - drop);
rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
prec = longDigitLength(rs);
drop = prec - mcp;
}
rb = null;
}
}
}
} catch(ArrayIndexOutOfBoundsException | NegativeArraySizeException e) {
NumberFormatException nfe = new NumberFormatException();
nfe.initCause(e);
throw nfe;
}
this.scale = scl;
this.precision = prec;
this.intCompact = rs;
this.intVal = rb;
}
/**
* Translates a character array representation of a
* {@code BigDecimal} into a {@code BigDecimal}, accepting the
* same sequence of characters as the {@link #BigDecimal(String)}
* constructor, while allowing a sub-array to be specified.
*
* @param in {@code char} array that is the source of characters.
* @param offset first character in the array to inspect.
* @param len number of characters to consider.
*
* @throws NumberFormatException if {@code in} is not a valid
* representation of a {@code BigDecimal} or the defined subarray
* is not wholly within {@code in}.
* @implNote If the sequence of characters is already available
* within a character array, using this constructor is faster than
* converting the {@code char} array to string and using the
* {@code BigDecimal(String)} constructor.
* @since 1.5
*/
/*
* ▶ 1-1
*
* 使用in[offset, offset+len-1]范围的字符序列构造BigDecimal,不会限制精度。
*/
public BigDecimal(char[] in, int offset, int len) {
this(in, offset, len, MathContext.UNLIMITED);
}
/**
* Translates a character array representation of a
* {@code BigDecimal} into a {@code BigDecimal}, accepting the
* same sequence of characters as the {@link #BigDecimal(String)}
* constructor.
*
* @param in {@code char} array that is the source of characters.
*
* @throws NumberFormatException if {@code in} is not a valid
* representation of a {@code BigDecimal}.
* @implNote If the sequence of characters is already available
* as a character array, using this constructor is faster than
* converting the {@code char} array to string and using the
* {@code BigDecimal(String)} constructor.
* @since 1.5
*/
/*
* ▶ 1-1-1
*
* 使用指定的字符序列构造BigDecimal,不会限制精度。
*/
public BigDecimal(char[] in) {
this(in, 0, in.length);
}
/**
* Translates the string representation of a {@code BigDecimal}
* into a {@code BigDecimal}. The string representation consists
* of an optional sign, {@code '+'} (<code> '\u002B'</code>) or
* {@code '-'} (<code>'\u002D'</code>), followed by a sequence of
* zero or more decimal digits ("the integer"), optionally
* followed by a fraction, optionally followed by an exponent.
*
* <p>The fraction consists of a decimal point followed by zero
* or more decimal digits. The string must contain at least one
* digit in either the integer or the fraction. The number formed
* by the sign, the integer and the fraction is referred to as the
* <i>significand</i>.
*
* <p>The exponent consists of the character {@code 'e'}
* (<code>'\u0065'</code>) or {@code 'E'} (<code>'\u0045'</code>)
* followed by one or more decimal digits. The value of the
* exponent must lie between -{@link Integer#MAX_VALUE} ({@link
* Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
*
* <p>More formally, the strings this constructor accepts are
* described by the following grammar:
* <blockquote>
* <dl>
* <dt><i>BigDecimalString:</i>
* <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
* <dt><i>Sign:</i>
* <dd>{@code +}
* <dd>{@code -}
* <dt><i>Significand:</i>
* <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>
* <dd>{@code .} <i>FractionPart</i>
* <dd><i>IntegerPart</i>
* <dt><i>IntegerPart:</i>
* <dd><i>Digits</i>
* <dt><i>FractionPart:</i>
* <dd><i>Digits</i>
* <dt><i>Exponent:</i>
* <dd><i>ExponentIndicator SignedInteger</i>
* <dt><i>ExponentIndicator:</i>
* <dd>{@code e}
* <dd>{@code E}
* <dt><i>SignedInteger:</i>
* <dd><i>Sign<sub>opt</sub> Digits</i>
* <dt><i>Digits:</i>
* <dd><i>Digit</i>
* <dd><i>Digits Digit</i>
* <dt><i>Digit:</i>
* <dd>any character for which {@link Character#isDigit}
* returns {@code true}, including 0, 1, 2 ...
* </dl>
* </blockquote>
*
* <p>The scale of the returned {@code BigDecimal} will be the
* number of digits in the fraction, or zero if the string
* contains no decimal point, subject to adjustment for any
* exponent; if the string contains an exponent, the exponent is
* subtracted from the scale. The value of the resulting scale
* must lie between {@code Integer.MIN_VALUE} and
* {@code Integer.MAX_VALUE}, inclusive.
*
* <p>The character-to-digit mapping is provided by {@link
* java.lang.Character#digit} set to convert to radix 10. The
* String may not contain any extraneous characters (whitespace,
* for example).
*
* <p><b>Examples:</b><br>
* The value of the returned {@code BigDecimal} is equal to
* <i>significand</i> × 10<sup> <i>exponent</i></sup>.
* For each string on the left, the resulting representation
* [{@code BigInteger}, {@code scale}] is shown on the right.
* <pre>
* "0" [0,0]
* "0.00" [0,2]
* "123" [123,0]
* "-123" [-123,0]
* "1.23E3" [123,-1]
* "1.23E+3" [123,-1]
* "12.3E+7" [123,-6]
* "12.0" [120,1]
* "12.3" [123,1]
* "0.00123" [123,5]
* "-1.23E-12" [-123,14]
* "1234.5E-4" [12345,5]
* "0E+7" [0,-7]
* "-0" [0,0]
* </pre>
*
* @param val String representation of {@code BigDecimal}.
*
* @throws NumberFormatException if {@code val} is not a valid
* representation of a {@code BigDecimal}.
* @apiNote For values other than {@code float} and
* {@code double} NaN and ±Infinity, this constructor is
* compatible with the values returned by {@link Float#toString}
* and {@link Double#toString}. This is generally the preferred
* way to convert a {@code float} or {@code double} into a
* BigDecimal, as it doesn't suffer from the unpredictability of
* the {@link #BigDecimal(double)} constructor.
*/
/*
* ▶ 1-1-2 (建议使用)
*
* 使用指定的字符串构造BigDecimal,不会限制精度。
*
* 字符串示例:
* "123" -> 123
* "1.23456789" -> 1.23456789
* "-1.234" -> -1.234
* "1.23456E3" -> 1234.56
* "-1.23456e-3" -> -0.00123456
*/
public BigDecimal(String val) {
this(val.toCharArray(), 0, val.length());
}
/**
* Translates a character array representation of a
* {@code BigDecimal} into a {@code BigDecimal}, accepting the
* same sequence of characters as the {@link #BigDecimal(String)}
* constructor and with rounding according to the context
* settings.
*
* @param in {@code char} array that is the source of characters.
* @param mc the context to use.
*
* @throws ArithmeticException if the result is inexact but the
* rounding mode is {@code UNNECESSARY}.
* @throws NumberFormatException if {@code in} is not a valid
* representation of a {@code BigDecimal}.
* @implNote If the sequence of characters is already available
* as a character array, using this constructor is faster than
* converting the {@code char} array to string and using the
* {@code BigDecimal(String)} constructor.
* @since 1.5