-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Money.java
954 lines (877 loc) · 31.1 KB
/
Money.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
/*
Copyright (c) 2012, 2023, Werner Keil and others by the @author tag.
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
*/
package org.javamoney.moneta;
import org.javamoney.moneta.format.ToStringMonetaryAmountFormat;
import org.javamoney.moneta.format.ToStringMonetaryAmountFormat.ToStringMonetaryAmountFormatStyle;
import org.javamoney.moneta.format.MonetaryAmountDecimalFormat;
import org.javamoney.moneta.spi.MoneyAmountFactory;
import org.javamoney.moneta.spi.DefaultNumberValue;
import org.javamoney.moneta.spi.MonetaryConfig;
import org.javamoney.moneta.spi.MoneyUtils;
import javax.money.*;
import javax.money.format.MonetaryAmountFormat;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Default immutable implementation of {@link MonetaryAmount} based
* on {@link BigDecimal} as numeric representation.
* <p>
* As required by {@link MonetaryAmount} this class is final, thread-safe,
* immutable and serializable.
* </p><p>
* This class can be configured with an arbitrary {@link MonetaryContext}. The
* default {@link MonetaryContext} used models by default the same settings as
* {@link MathContext#DECIMAL64} . This default {@link MonetaryContext} can also
* be reconfigured by adding a file {@code /javamoney.properties} to the
* classpath, with the following content:
* </p>
* <pre>
* # Default MathContext for Money
* #-------------------------------
* # Custom MonetaryContext, overrides default entries from
* # org.javamoney.moneta.Money.monetaryContext
* # RoundingMode hereby is optional (default = HALF_EVEN)
* org.javamoney.moneta.Money.defaults.precision=256
* org.javamoney.moneta.Money.defaults.roundingMode=HALF_EVEN
* </pre>
*
* @author Anatole Tresch
* @author Werner Keil
* @version 1.3
* @since 1.0
*/
public final class Money implements MonetaryAmount, Comparable<MonetaryAmount>, Serializable {
/**
* serialVersionUID.
*/
private static final long serialVersionUID = -7565813772046251748L;
/**
* The default {@link MonetaryContext} applied, if not set explicitly on
* creation.
*/
public static final MonetaryContext DEFAULT_MONETARY_CONTEXT = new DefaultMonetaryContextFactory().getContext();
/**
* The currency of this amount.
*/
private final CurrencyUnit currency;
/**
* the {@link MonetaryContext} used by this instance, e.g. on division.
*/
private final MonetaryContext monetaryContext;
/**
* The numeric part of this amount.
*/
private final BigDecimal number;
/**
* Creates a new instance of {@link Money}.
*
* @param currency the currency, not null.
* @param number the amount, not null.
* @throws ArithmeticException If the number exceeds the capabilities of the default
* {@link MonetaryContext}.
*/
private Money(BigDecimal number, CurrencyUnit currency) {
this(number, currency, null);
}
/**
* Creates a new instance of {@link Money}.
*
* @param currency the currency, not {@code null}.
* @param number the amount, not {@code null}.
* @param monetaryContext the {@link MonetaryContext}, if {@code null}, the default is
* used.
* @throws ArithmeticException If the number exceeds the capabilities of the
* {@link MonetaryContext} used.
*/
private Money(BigDecimal number, CurrencyUnit currency, MonetaryContext monetaryContext) {
Objects.requireNonNull(currency, "Currency is required.");
this.currency = currency;
if (Objects.nonNull(monetaryContext)) {
this.monetaryContext = monetaryContext;
} else {
this.monetaryContext = DEFAULT_MONETARY_CONTEXT;
}
Objects.requireNonNull(number, "Number is required.");
this.number = MoneyUtils.getBigDecimal(number, this.monetaryContext);
}
/**
* Returns the amount’s currency, modelled as {@link CurrencyUnit}.
* Implementations may co-variantly change the return type to a more
* specific implementation of {@link CurrencyUnit} if desired.
*
* @return the currency, never {@code null}
* @see javax.money.MonetaryAmount#getCurrency()
*/
@Override
public CurrencyUnit getCurrency() {
return currency;
}
/**
* Access the {@link MonetaryContext} used by this instance.
*
* @return the {@link MonetaryContext} used, never null.
* @see javax.money.MonetaryAmount#getContext()
*/
@Override
public MonetaryContext getContext() {
return monetaryContext;
}
/**
* Gets the number representation of the numeric value of this item.
*
* @return The {@link Number} representation matching best.
*/
@Override
public NumberValue getNumber() {
return new DefaultNumberValue(number);
}
/**
* Method that returns BigDecimal.ZERO, if {@link #isZero()}, and
* {@link #number #stripTrailingZeros()} in all other cases.
*
* @return the stripped number value.
*/
public BigDecimal getNumberStripped() {
if (isZero()) {
return BigDecimal.ZERO;
}
return this.number.stripTrailingZeros();
}
/*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(MonetaryAmount o) {
Objects.requireNonNull(o);
int compare = getCurrency().getCurrencyCode().compareTo(o.getCurrency().getCurrencyCode());
if (compare == 0) {
compare = this.number.compareTo(Money.from(o).number);
}
return compare;
}
// Arithmetic Operations
/*
* (non-Javadoc)
*
* @see MonetaryAmount#abs()
*/
@Override
public Money abs() {
if (this.isPositiveOrZero()) {
return this;
}
return negate();
}
/*
* (non-Javadoc)
*
* @see MonetaryAmount#divide(MonetaryAmount)
*/
@Override
public Money divide(long divisor) {
if (divisor == 1L) {
return this;
}
return divide(BigDecimal.valueOf(divisor));
}
/*
* (non-Javadoc)
*
* @see MonetaryAmount#divide(MonetaryAmount)
*/
@Override
public Money divide(double divisor) {
if (NumberVerifier.isInfinityAndNotNaN(divisor)) {
return Money.of(0, getCurrency());
}
if (divisor == 1.0d) {
return this;
}
return divide(new BigDecimal(String.valueOf(divisor)));
}
/*
* (non-Javadoc)
*
* @see
* MonetaryAmount#divideAndRemainder(MonetaryAmount)
*/
@Override
public Money[] divideAndRemainder(long divisor) {
return divideAndRemainder(BigDecimal.valueOf(divisor));
}
/*
* (non-Javadoc)
*
* @see
* MonetaryAmount#divideAndRemainder(MonetaryAmount)
*/
@Override
public Money[] divideAndRemainder(double divisor) {
if (NumberVerifier.isInfinityAndNotNaN(divisor)) {
Money zero = Money.of(0, getCurrency());
return new Money[]{zero, zero};
}
return divideAndRemainder(new BigDecimal(String.valueOf(divisor)));
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#multiply(Number)
*/
@Override
public Money multiply(long multiplicand) {
if (multiplicand == 1L) {
return this;
}
return multiply(BigDecimal.valueOf(multiplicand));
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#multiply(Number)
*/
@Override
public Money multiply(double multiplicand) {
NumberVerifier.checkNoInfinityOrNaN(multiplicand);
if (multiplicand == 1.0d) {
return this;
}
return multiply(new BigDecimal(String.valueOf(multiplicand)));
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#remainder(Number)
*/
@Override
public Money remainder(long divisor) {
return remainder(BigDecimal.valueOf(divisor));
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#remainder(Number)
*/
@Override
public Money remainder(double divisor) {
if (NumberVerifier.isInfinityAndNotNaN(divisor)) {
return Money.of(0, getCurrency());
}
return remainder(new BigDecimal(String.valueOf(divisor)));
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#isZero()
*/
@Override
public boolean isZero() {
return signum() == 0;
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#isPositive()
*/
@Override
public boolean isPositive() {
return signum() == 1;
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#isPositiveOrZero()
*/
@Override
public boolean isPositiveOrZero() {
return signum() >= 0;
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#isNegative()
*/
@Override
public boolean isNegative() {
return signum() == -1;
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#isNegativeOrZero()
*/
@Override
public boolean isNegativeOrZero() {
return signum() <= 0;
}
/**
* Returns the scale of this <type>Money</type>. 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. For example, a scale of -3 means the unscaled value is multiplied by 1000.
* @return the scale of this <type>Money</type>.
* @see java.math.BigDecimal#scale()
* @since 1.3
*/
public int getScale() {
return number.scale();
}
/**
* Returns the precision of this <type>RoundedMoney</type>. (The precision is the number of digits in the unscaled value.)
* The precision of a zero value is 1.
* @return the precision of this <type>RoundedMoney</type>.
* @see BigDecimal#precision()
* @since 1.3
*/
public int getPrecision() {
return number.precision();
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#query(javax.money.MonetaryQuery)
*/
@Override
public <R> R query(MonetaryQuery<R> query) {
Objects.requireNonNull(query);
try {
return query.queryFrom(this);
} catch (MonetaryException e) {
throw e;
} catch (Exception e) {
throw new MonetaryException("Query failed: " + query, e);
}
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#with(javax.money.MonetaryOperator)
*/
@Override
public Money with(MonetaryOperator operator) {
Objects.requireNonNull(operator);
try {
return Money.class.cast(operator.apply(this));
} catch (MonetaryException e) {
throw e;
} catch (Exception e) {
throw new MonetaryException("Operator failed: " + operator, e);
}
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#add(javax.money.MonetaryAmount)
*/
@Override
public Money add(MonetaryAmount amount) {
MoneyUtils.checkAmountParameter(amount, this.currency);
if (amount.isZero()) {
return this;
}
MathContext mc = MoneyUtils.getMathContext(monetaryContext, RoundingMode.HALF_EVEN);
return new Money(this.number.add(amount.getNumber().numberValue(BigDecimal.class), mc), getCurrency(), monetaryContext);
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#divide(java.lang.Number)
*/
@Override
public Money divide(Number divisor) {
if (NumberVerifier.isInfinityAndNotNaN(divisor)) {
return Money.of(0, getCurrency());
}
BigDecimal divisorBD = MoneyUtils.getBigDecimal(divisor);
if (divisorBD.equals(BigDecimal.ONE)) {
return this;
}
MathContext mc = MoneyUtils.getMathContext(monetaryContext, RoundingMode.HALF_EVEN);
int maxScale = monetaryContext.getMaxScale();
if(maxScale>0){
return new Money(this.number.divide(divisorBD, maxScale, mc.getRoundingMode()), getCurrency(), monetaryContext);
}
return new Money(this.number.divide(divisorBD, mc), getCurrency(), monetaryContext);
}
@Override
public Money[] divideAndRemainder(Number divisor) {
if (NumberVerifier.isInfinityAndNotNaN(divisor)) {
Money zero = Money.of(0, getCurrency());
return new Money[]{zero, zero};
}
BigDecimal divisorBD = MoneyUtils.getBigDecimal(divisor);
if (divisorBD.equals(BigDecimal.ONE)) {
return new Money[]{this, new Money(BigDecimal.ZERO, getCurrency())};
}
MathContext mc = MoneyUtils.getMathContext(monetaryContext, RoundingMode.HALF_EVEN);
BigDecimal[] dec = this.number.divideAndRemainder(divisorBD, mc);
return new Money[]{new Money(dec[0], getCurrency(), monetaryContext), new Money(dec[1], getCurrency(), monetaryContext)};
}
/*
* (non-Javadoc)
*
* @see
* org.javamoney.moneta.AbstractMoney#divideToIntegralValue(java.lang.Number
* )
*/
@Override
public Money divideToIntegralValue(long divisor) {
return divideToIntegralValue(MoneyUtils.getBigDecimal(divisor));
}
@Override
public Money divideToIntegralValue(double divisor) {
if (NumberVerifier.isInfinityAndNotNaN(divisor)) {
return Money.of(0, getCurrency());
}
return divideToIntegralValue(MoneyUtils.getBigDecimal(divisor));
}
@Override
public Money divideToIntegralValue(Number divisor) {
if (NumberVerifier.isInfinityAndNotNaN(divisor)) {
return Money.of(0, getCurrency());
}
MathContext mc = MoneyUtils.getMathContext(monetaryContext, RoundingMode.HALF_EVEN);
BigDecimal divisorBD = MoneyUtils.getBigDecimal(divisor);
BigDecimal dec = this.number.divideToIntegralValue(divisorBD, mc);
return new Money(dec, getCurrency(), monetaryContext);
}
/*
* (non-Javadoc)
*
* @see org.javamoney.moneta.AbstractMoney#multiply(java.lang.Number)
*/
@Override
public Money multiply(Number multiplicand) {
NumberVerifier.checkNoInfinityOrNaN(multiplicand);
BigDecimal multiplicandBD = MoneyUtils.getBigDecimal(multiplicand);
if (multiplicandBD.equals(BigDecimal.ONE)) {
return this;
}
MathContext mc = MoneyUtils.getMathContext(monetaryContext, RoundingMode.HALF_EVEN);
BigDecimal dec = this.number.multiply(multiplicandBD, mc);
return new Money(dec, getCurrency(), monetaryContext);
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#negate()
*/
@Override
public Money negate() {
return new Money(this.number.negate(), getCurrency());
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#plus()
*/
@Override
public Money plus() {
return this;
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#subtract(javax.money.MonetaryAmount)
*/
@Override
public Money subtract(MonetaryAmount subtrahend) {
MoneyUtils.checkAmountParameter(subtrahend, this.currency);
if (subtrahend.isZero()) {
return this;
}
MathContext mc = MoneyUtils.getMathContext(monetaryContext, RoundingMode.HALF_EVEN);
return new Money(this.number.subtract(subtrahend.getNumber().numberValue(BigDecimal.class), mc), getCurrency(),
monetaryContext);
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#stripTrailingZeros()
*/
@Override
public Money stripTrailingZeros() {
if (isZero()) {
return new Money(BigDecimal.ZERO, getCurrency());
}
return new Money(this.number.stripTrailingZeros(), getCurrency(), monetaryContext);
}
/*
* (non-Javadoc)
*
* @see org.javamoney.moneta.AbstractMoney#remainder(java.math.BigDecimal)
*/
@Override
public Money remainder(Number divisor) {
if (NumberVerifier.isInfinityAndNotNaN(divisor)) {
return new Money(BigDecimal.ZERO, getCurrency());
}
MathContext mc = MoneyUtils.getMathContext(monetaryContext, RoundingMode.HALF_EVEN);
BigDecimal bd = MoneyUtils.getBigDecimal(divisor);
return new Money(this.number.remainder(bd, mc), getCurrency(), monetaryContext);
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#scaleByPowerOfTen(int)
*/
@Override
public Money scaleByPowerOfTen(int power) {
return new Money(this.number.scaleByPowerOfTen(power), getCurrency(),
monetaryContext);
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#signum()
*/
@Override
public int signum() {
return this.number.signum();
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#isLessThan(javax.money.MonetaryAmount)
*/
@Override
public boolean isLessThan(MonetaryAmount amount) {
MoneyUtils.checkAmountParameter(amount, this.currency);
return number.stripTrailingZeros()
.compareTo(amount.getNumber().numberValue(BigDecimal.class).stripTrailingZeros()) < 0;
}
/*
* (non-Javadoc)
*
* @see
* javax.money.MonetaryAmount#isLessThanOrEqualTo(javax.money.MonetaryAmount
* )
*/
@Override
public boolean isLessThanOrEqualTo(MonetaryAmount amount) {
MoneyUtils.checkAmountParameter(amount, this.currency);
return number.stripTrailingZeros()
.compareTo(amount.getNumber().numberValue(BigDecimal.class).stripTrailingZeros()) <= 0;
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#isGreaterThan(javax.money.MonetaryAmount)
*/
@Override
public boolean isGreaterThan(MonetaryAmount amount) {
MoneyUtils.checkAmountParameter(amount, this.currency);
return number.stripTrailingZeros()
.compareTo(amount.getNumber().numberValue(BigDecimal.class).stripTrailingZeros()) > 0;
}
/*
* (non-Javadoc)
*
* @see
* javax.money.MonetaryAmount#isGreaterThanOrEqualTo(javax.money.MonetaryAmount
* ) #see
*/
@Override
public boolean isGreaterThanOrEqualTo(MonetaryAmount amount) {
MoneyUtils.checkAmountParameter(amount, this.currency);
return number.stripTrailingZeros()
.compareTo(amount.getNumber().numberValue(BigDecimal.class).stripTrailingZeros()) >= 0;
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#isEqualTo(javax.money.MonetaryAmount)
*/
@Override
public boolean isEqualTo(MonetaryAmount amount) {
MoneyUtils.checkAmountParameter(amount, this.currency);
return number.stripTrailingZeros()
.compareTo(amount.getNumber().numberValue(BigDecimal.class).stripTrailingZeros()) == 0;
}
/*
* (non-Javadoc)
*
* @see javax.money.MonetaryAmount#getFactory()
*/
@Override
public MonetaryAmountFactory<Money> getFactory() {
return new MoneyAmountFactory().setAmount(this);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Money) {
Money other = (Money) obj;
return getCurrency().equals(other.getCurrency()) &&
this.number.compareTo(other.number) == 0;
}
return false;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
try {
//MonetaryAmount amount = Monetary.getDefaultRounding().apply(this);
return defaultFormat().format(this);
}catch(Exception e) {
return getCurrency().getCurrencyCode() + ' ' + number.toPlainString();
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return Objects.hash(getCurrency(), getNumberStripped());
}
/**
* Creates a new instance of {@link Money}, using the default
* {@link MonetaryContext}.
*
* @param number numeric value, not {@code null}.
* @param currency currency unit, not {@code null}.
* @return a {@code Money} combining the numeric value and currency unit.
* @throws ArithmeticException If the number exceeds the capabilities of the default
* {@link MonetaryContext} used.
*/
public static Money of(BigDecimal number, CurrencyUnit currency) {
return new Money(number, currency);
}
/**
* Creates a new instance of {@link Money}, using an explicit
* {@link MonetaryContext}.
*
* @param number numeric value, not {@code null}.
* @param currency currency unit, not {@code null}.
* @param monetaryContext the {@link MonetaryContext} to be used, if {@code null} the
* default {@link MonetaryContext} is used.
* @return a {@code Money} instance based on the monetary context with the
* given numeric value, currency unit.
* @throws ArithmeticException If the number exceeds the capabilities of the
* {@link MonetaryContext} used.
*/
public static Money of(BigDecimal number, CurrencyUnit currency, MonetaryContext monetaryContext) {
return new Money(number, currency, monetaryContext);
}
/**
* Creates a new instance of {@link Money}, using the default
* {@link MonetaryContext}.
*
* @param currency The target currency, not null.
* @param number The numeric part, not null.
* @return A new instance of {@link Money}.
* @throws ArithmeticException If the number exceeds the capabilities of the default
* {@link MonetaryContext} used.
*/
public static Money of(Number number, CurrencyUnit currency) {
return new Money(MoneyUtils.getBigDecimal(number), currency);
}
/**
* Creates a new instance of {@link Money}, using an explicit
* {@link MonetaryContext}.
*
* @param currency The target currency, not null.
* @param number The numeric part, not null.
* @param monetaryContext the {@link MonetaryContext} to be used, if {@code null} the
* default {@link MonetaryContext} is used.
* @return A new instance of {@link Money}.
* @throws ArithmeticException If the number exceeds the capabilities of the
* {@link MonetaryContext} used.
*/
public static Money of(Number number, CurrencyUnit currency, MonetaryContext monetaryContext) {
return new Money(MoneyUtils.getBigDecimal(number), currency, monetaryContext);
}
/**
* Static factory method for creating a new instance of {@link Money}.
*
* @param currencyCode The target currency as ISO currency code.
* @param number The numeric part, not null.
* @return A new instance of {@link Money}.
*/
public static Money of(Number number, String currencyCode) {
return new Money(MoneyUtils.getBigDecimal(number), Monetary.getCurrency(currencyCode));
}
/**
* Static factory method for creating a new instance of {@link Money}.
*
* @param currencyCode The target currency as ISO currency code.
* @param number The numeric part, not null.
* @return A new instance of {@link Money}.
*/
public static Money of(BigDecimal number, String currencyCode) {
return new Money(number, Monetary.getCurrency(currencyCode));
}
/**
* Static factory method for creating a new instance of {@link Money}.
*
* @param currencyCode The target currency as ISO currency code.
* @param number The numeric part, not null.
* @param monetaryContext the {@link MonetaryContext} to be used, if {@code null} the
* default {@link MonetaryContext} is used.
* @return A new instance of {@link Money}.
*/
public static Money of(Number number, String currencyCode, MonetaryContext monetaryContext) {
return new Money(MoneyUtils.getBigDecimal(number), Monetary.getCurrency(currencyCode),
monetaryContext);
}
/**
* Static factory method for creating a new instance of {@link Money}.
*
* @param currencyCode The target currency as ISO currency code.
* @param number The numeric part, not null.
* @param monetaryContext the {@link MonetaryContext} to be used, if {@code null} the
* default {@link MonetaryContext} is used.
* @return A new instance of {@link Money}.
*/
public static Money of(BigDecimal number, String currencyCode, MonetaryContext monetaryContext) {
return new Money(number, Monetary.getCurrency(currencyCode), monetaryContext);
}
/**
* Obtains an instance of {@link Money} representing zero.
* @param currency the currency, not null.
* @return an instance of {@link Money} representing zero.
* @since 1.0.1
*/
public static Money zero(CurrencyUnit currency) {
return new Money(BigDecimal.ZERO, currency);
}
/**
* Obtains an instance of {@code Money} from an amount in minor units.
* For example, {@code ofMinor(USD, 1234)} creates the instance {@code USD 12.34}.
* @param currency the currency
* @param amountMinor the amount of money in the minor division of the currency
* @return the Money from minor units
* @throws NullPointerException when the currency is null
* @throws IllegalArgumentException when {@link CurrencyUnit#getDefaultFractionDigits()} is lesser than zero.
* @see CurrencyUnit#getDefaultFractionDigits()
* @since 1.0.1
*/
public static Money ofMinor(CurrencyUnit currency, long amountMinor) {
return ofMinor(currency, amountMinor, currency.getDefaultFractionDigits());
}
/**
* Obtains an instance of {@code Money} from an amount in minor units.
* For example, {@code ofMinor(USD, 1234, 2)} creates the instance {@code USD 12.34}.
* @param currency the currency, not null
* @param amountMinor the amount of money in the minor division of the currency
* @param fractionDigits number of digits
* @return the monetary amount from minor units
* @see CurrencyUnit#getDefaultFractionDigits()
* @see Money#ofMinor(CurrencyUnit, long, int)
* @throws NullPointerException when the currency is null
* @throws IllegalArgumentException when the fractionDigits is negative
* @since 1.0.1
*/
public static Money ofMinor(CurrencyUnit currency, long amountMinor, int fractionDigits) {
if(fractionDigits < 0) {
throw new IllegalArgumentException("The fractionDigits cannot be negative");
}
return of(BigDecimal.valueOf(amountMinor, fractionDigits), currency);
}
/**
* Converts (if necessary) the given {@link MonetaryAmount} to a
* {@link Money} instance. The {@link MonetaryContext} will be adapted as
* necessary, if the precision of the given amount exceeds the capabilities
* of the default {@link MonetaryContext}.
*
* @param amt the amount to be converted
* @return an according Money instance.
*/
public static Money from(MonetaryAmount amt) {
if (amt.getClass() == Money.class) {
return (Money) amt;
}
return Money.of(amt.getNumber().numberValue(BigDecimal.class), amt.getCurrency(), amt.getContext());
}
/**
* Obtains an instance of Money from a text string such as 'EUR 25.25'.
*
* @param text the text to parse not null
* @return Money instance
* @throws NumberFormatException if the amount is not a number
* @throws UnknownCurrencyException if the currency cannot be resolved
*/
public static Money parse(CharSequence text) {
return parse(text, defaultFormat());
}
/**
* Obtains an instance of Money from a text using specific formatter.
*
* @param text the text to parse not null
* @param formatter the formatter to use not null
* @return Money instance
*/
public static Money parse(CharSequence text, MonetaryAmountFormat formatter) {
return from(formatter.parse(text));
}
private static MonetaryAmountFormat defaultFormat() {
final String useJDK = MonetaryConfig.getConfig().getOrDefault("org.javamoney.moneta.useJDKdefaultFormat", "false");
try {
if(Boolean.parseBoolean(useJDK)){
Logger.getLogger(Money.class.getName()).fine("Using JDK formatter for toString().");
return MonetaryAmountDecimalFormat.of();
} else {
Logger.getLogger(Money.class.getName()).fine("Using default formatter for toString().");
return ToStringMonetaryAmountFormat.of(ToStringMonetaryAmountFormatStyle.MONEY);
}
} catch(Exception e) {
Logger.getLogger(Money.class.getName()).log(Level.WARNING,
"Invalid boolean parameter for 'org.javamoney.moneta.useJDKdefaultFormat', " +
"using default formatter for toString().");
return ToStringMonetaryAmountFormat.of(ToStringMonetaryAmountFormatStyle.MONEY);
}
}
/**
* Just to don't break the compatibility.
* Don't use it
* @param number the amount, not null
* @deprecated Will be removed.
* @see NumberVerifier#isInfinityAndNotNaN
*/
@Deprecated
public static boolean isInfinityAndNotNaN(Number number) {
if (Double.class == number.getClass() || Float.class == number.getClass()) {
double dValue = number.doubleValue();
if (!Double.isNaN(dValue) && Double.isInfinite(dValue)) {
return true;
}
}
return false;
}
/**
* Just to don't break the compatibility.
* Don't use it
* @param number the amount, not null.
* @deprecated Will be removed. Use
* @see NumberVerifier#checkNoInfinityOrNaN
*/
@Deprecated
public static void checkNoInfinityOrNaN(Number number) {
NumberVerifier.checkNoInfinityOrNaN(number);
}
}