-
Notifications
You must be signed in to change notification settings - Fork 19
/
Amount.java
982 lines (900 loc) · 33.6 KB
/
Amount.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
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - info@scireum.de
*/
package sirius.kernel.commons;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import sirius.kernel.nls.NLS;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Provides a wrapper around <tt>BigDecimal</tt> to perform "exact" computations on numeric values.
* <p>
* Adds some extended computations as well as locale aware formatting options to perform "exact" computations on
* numeric value. The internal representation is <tt>BigDecimal</tt> and uses MathContext.DECIMAL128 for
* numerical operations. Also, the scale of each value is fixed to 5 decimal places after the comma, since this is
* enough for most business applications and rounds away any rounding errors introduced by doubles.
* <p>
* A textual representation can be created by calling one of the <tt>toString</tt> methods or by supplying
* a {@link NumberFormat}.
* <p>
* Note that {@link #toMachineString()} to be used to obtain a technical representation suitable for file formats
* like XML etc. This is also used by {@link NLS#toMachineString(Object)}. The default representation uses two
* decimal digits. However, if the amount has bed {@link #round(int, RoundingMode) rounded}, the given amount
* of decimals will be used in all subsequent call to {@link #toMachineString()}. Therefore, this can be used to
* control the exact formatting (e.g. when writing XML or JSON).
* <p>
* Being able to be <i>empty</i>, this class handles <tt>null</tt> values gracefully, which simplifies many operations.
*
* @see NumberFormat
* @see BigDecimal
*/
@Immutable
public class Amount extends Number implements Comparable<Amount>, Serializable {
@Serial
private static final long serialVersionUID = 2187873067365153302L;
/**
* Represents an missing number. This is also the result of division by 0 and other forbidden operations.
*/
public static final Amount NOTHING = new Amount(null, false);
/**
* Representation of 100.00
*/
public static final Amount ONE_HUNDRED = Amount.of(new BigDecimal(100));
/**
* Representation of 0.00
*/
public static final Amount ZERO = Amount.of(BigDecimal.ZERO);
/**
* Representation of 1.00
*/
public static final Amount ONE = Amount.of(BigDecimal.ONE);
/**
* Representation of 10.00
*/
public static final Amount TEN = Amount.of(BigDecimal.TEN);
/**
* Representation of -1.00
*/
public static final Amount MINUS_ONE = Amount.of(new BigDecimal(-1));
/**
* Defines the internal precision used for all computations.
*/
public static final int SCALE = 5;
private static final String[] METRICS = {"f", "n", "u", "m", "", "K", "M", "G"};
private static final int NEUTRAL_METRIC = 4;
private final BigDecimal value;
private final boolean rounded;
private Amount(BigDecimal value, boolean rounded) {
this.value = value;
this.rounded = rounded;
}
/**
* Converts the given string into a number. If the string is empty, <tt>NOTHING</tt> is returned.
* If the string is malformed an exception will be thrown.
*
* @param value the string value which should be converted into a numeric value.
* @return an <tt>Amount</tt> representing the given input. <tt>NOTHING</tt> if the input was empty.
*/
@Nonnull
public static Amount ofMachineString(@Nullable String value) {
if (Strings.isEmpty(value)) {
return NOTHING;
}
return of(NLS.parseMachineString(BigDecimal.class, value));
}
/**
* Converts the given string into a number which is formatted according the decimal symbols for the current locale.
*
* @param value the string value which should be converted into a numeric value.
* @return an {@code Amount} representing the given input. {@code NOTHING} if the input was empty.
* @see NLS
*/
@Nonnull
public static Amount ofUserString(@Nullable String value) {
if (Strings.isEmpty(value)) {
return NOTHING;
}
return NLS.parseUserString(Amount.class, value);
}
/**
* Converts the given value into a number.
* <p>
* Note that this will enforce a scale of {@link #SCALE} (5) for the given value to ensure a consistent
* behaviour. If the given value already has the desired scale set, use {@link #ofRounded(BigDecimal)}.
*
* @param amount the value which should be converted into an <tt>Amount</tt>
* @return an <tt>Amount</tt> representing the given input. <tt>NOTHING</tt> if the input was empty.
*/
@Nonnull
@JsonCreator
public static Amount of(@Nullable BigDecimal amount) {
if (amount == null) {
return NOTHING;
}
return new Amount(amount.setScale(SCALE, RoundingMode.HALF_UP), false);
}
/**
* Converts the given value into a number.
* <p>
* Note that this keeps the scale of the given value as it presumes that it has already been
* set to the desired value.
*
* @param amount the value which should be converted into an <tt>Amount</tt>
* @return an <tt>Amount</tt> representing the given input. <tt>NOTHING</tt> if the input was empty.
*/
@Nonnull
public static Amount ofRounded(@Nullable BigDecimal amount) {
if (amount == null) {
return NOTHING;
}
return new Amount(amount, true);
}
/**
* Converts the given value into a number.
*
* @param amount the value which should be converted into an <tt>Amount</tt>
* @return an <tt>Amount</tt> representing the given input
*/
@Nonnull
public static Amount of(int amount) {
return of(new BigDecimal(amount));
}
/**
* Converts the given value into a number.
*
* @param amount the value which should be converted into an <tt>Amount</tt>
* @return an <tt>Amount</tt> representing the given input
*/
@Nonnull
public static Amount of(long amount) {
return of(new BigDecimal(amount));
}
/**
* Converts the given value into a number.
*
* @param amount the value which should be converted into an <tt>Amount</tt>
* @return an <tt>Amount</tt> representing the given input
*/
@Nonnull
public static Amount of(double amount) {
if (Double.isInfinite(amount) || Double.isNaN(amount)) {
return NOTHING;
}
return of(BigDecimal.valueOf(amount));
}
/**
* Converts the given value into a number.
*
* @param amount the value which should be converted into an <tt>Amount</tt>
* @return an <tt>Amount</tt> representing the given input. <tt>NOTHING</tt> if the input was empty.
*/
@Nonnull
public static Amount of(@Nullable Integer amount) {
if (amount == null) {
return NOTHING;
}
return of(new BigDecimal(amount));
}
/**
* Converts the given value into a number.
*
* @param amount the value which should be converted into an <tt>Amount</tt>
* @return an <tt>Amount</tt> representing the given input. <tt>NOTHING</tt> if the input was empty.
*/
@Nonnull
public static Amount of(@Nullable Long amount) {
if (amount == null) {
return NOTHING;
}
return of(new BigDecimal(amount));
}
/**
* Converts the given value into a number.
*
* @param amount the value which should be converted into an <tt>Amount</tt>
* @return an <tt>Amount</tt> representing the given input. <tt>NOTHING</tt> if the input was empty.
*/
@Nonnull
public static Amount of(@Nullable Double amount) {
if (amount == null || Double.isInfinite(amount) || Double.isNaN(amount)) {
return NOTHING;
}
return of(BigDecimal.valueOf(amount));
}
/**
* Unwraps the internally used <tt>BigDecimal</tt>. May be <tt>null</tt> if this <tt>Amount</tt> is
* <tt>NOTHING</tt>.
*
* @return the internally used <tt>BigDecimal</tt>
*/
@Nullable
public BigDecimal getAmount() {
return value;
}
/**
* Unwraps the internally used <tt>BigDecimal</tt> like {@link #getAmount()}, but also strips trailing zeros from
* the decimal part.
*
* @return the amount with trailing zeros stripped of the decimal part
*/
@Nullable
public BigDecimal fetchAmountWithoutTrailingZeros() {
return Optional.ofNullable(value)
.map(BigDecimal::stripTrailingZeros)
.map(bigDecimal -> bigDecimal.scale() < 0 ?
bigDecimal.setScale(0, RoundingMode.UNNECESSARY) :
bigDecimal)
.orElse(null);
}
/**
* Unwraps the internally used <tt>BigDecimal</tt> with rounding like in {@link #toMachineString()} applied.
* This is used for Jackson Object Mapping.
*
* @return the internally used <tt>BigDecimal</tt> with rounding applied
*/
@Nullable
@JsonValue
private BigDecimal getRoundedAmount() {
if (rounded) {
return getAmount();
} else {
return round(2, RoundingMode.HALF_UP).getAmount();
}
}
@Override
public int intValue() {
throwExceptionIfEmpty();
return value.intValue();
}
@Override
public long longValue() {
throwExceptionIfEmpty();
return value.longValue();
}
@Override
public float floatValue() {
throwExceptionIfEmpty();
return value.floatValue();
}
@Override
public double doubleValue() {
throwExceptionIfEmpty();
return value.doubleValue();
}
/**
* Checks if this contains no value.
*
* @return <tt>true</tt> if the internal value is null, <tt>false</tt> otherwise
*/
public boolean isEmpty() {
return value == null;
}
/**
* Checks if this actual number contains a value or not
*
* @return <tt>true</tt> if the internal value is a number, <tt>false</tt> otherwise
*/
public boolean isFilled() {
return value != null;
}
/**
* If this actual number if empty, the given value will be returned. Otherwise this will be returned.
*
* @param valueIfNothing the value which is used if there is no internal value
* @return <tt>this</tt> if there is an internal value, <tt>valueIfNothing</tt> otherwise
*/
@Nonnull
public Amount fill(@Nonnull Amount valueIfNothing) {
if (isEmpty()) {
return valueIfNothing;
} else {
return this;
}
}
/**
* Invokes the given consumer if the internal value is not empty.
*
* @param consumer the consumer to execute
*/
public void ifPresent(Consumer<Amount> consumer) {
if (isFilled()) {
consumer.accept(this);
}
}
/**
* Executes the given runnable if the internal value is empty.
*
* @param runnable the runnable to execute
*/
public void ifEmpty(Runnable runnable) {
if (isEmpty()) {
runnable.run();
}
}
/**
* Returns the provided alternative {@link Amount} if the internal value is empty.
*
* @param amount the alternative Amount to return
* @return the original or alternative amount
*/
public Amount orElse(Amount amount) {
if (isEmpty()) {
return amount;
}
return this;
}
/**
* Computes a value using the provided supplier if the internal value is empty.
*
* @param supplier the supplier which is used to compute a value if there is no internal value
* @return <tt>this</tt> if there is an internal value, the computed value of <tt>supplier</tt> otherwise
*/
@Nonnull
public Amount orElseGet(Supplier<Amount> supplier) {
if (isEmpty()) {
return supplier.get();
}
return this;
}
/**
* Increases this number by the given amount in percent. If <tt>increase</tt> is 18 and the value of this is 100,
* the result would by 118.
*
* @param increase the percent value by which the value of this will be increased
* @return <tt>NOTHING</tt> if <tt>this</tt> is empty, {@code this * (1 + increase / 100)} otherwise
*/
@Nonnull
@CheckReturnValue
public Amount increasePercent(@Nonnull Amount increase) {
return times(ONE.add(increase.asDecimal()));
}
/**
* Decreases this number by the given amount in percent. If <tt>decrease</tt> is 10 and the value of this is 100,
* the result would by 90.
*
* @param decrease the percent value by which the value of this will be decreased
* @return <tt>NOTHING</tt> if <tt>this</tt> is empty, {@code this * (1 - increase / 100)} otherwise
*/
@Nonnull
@CheckReturnValue
public Amount decreasePercent(@Nonnull Amount decrease) {
return times(ONE.subtract(decrease.asDecimal()));
}
/**
* Adds the given number to <tt>this</tt>, if <tt>other</tt> is not empty. Otherwise, <tt>this</tt> will be
* returned.
*
* @param other the operand to add to this.
* @return an <tt>Amount</tt> representing the sum of <tt>this</tt> and <tt>other</tt> if both values were filled.
* If <tt>other</tt> is empty, <tt>this</tt> is returned. If this is empty, <tt>NOTHING</tt> is returned.
*/
@Nonnull
@CheckReturnValue
public Amount add(@Nullable Amount other) {
if (other == null || other.isEmpty()) {
return this;
}
if (isEmpty()) {
return NOTHING;
}
return Amount.of(value.add(other.value));
}
/**
* Subtracts the given number from <tt>this</tt>, if <tt>other</tt> is not empty. Otherwise <tt>this</tt> will be
* returned.
*
* @param other the operand to subtract from this.
* @return an <tt>Amount</tt> representing the difference of <tt>this</tt> and <tt>other</tt> if both values were
* filled.
* If <tt>other</tt> is empty, <tt>this</tt> is returned. If this is empty, <tt>NOTHING</tt> is returned.
*/
@Nonnull
@CheckReturnValue
public Amount subtract(@Nullable Amount other) {
if (other == null || other.isEmpty()) {
return this;
}
if (isEmpty()) {
return NOTHING;
}
return Amount.of(value.subtract(other.value));
}
/**
* Multiplies the given number with <tt>this</tt>. If either of both is empty, <tt>NOTHING</tt> will be returned.
*
* @param other the operand to multiply with this.
* @return an <tt>Amount</tt> representing the product of <tt>this</tt> and <tt>other</tt> if both values were
* filled.
* If <tt>other</tt> is empty or if <tt>this</tt> is empty, <tt>NOTHING</tt> is returned.
*/
@Nonnull
@CheckReturnValue
public Amount times(@Nonnull Amount other) {
if (other.isEmpty() || isEmpty()) {
return NOTHING;
}
return Amount.of(value.multiply(other.value));
}
/**
* Divides <tt>this</tt> by the given number. If either of both is empty, or the given number is zero,
* <tt>NOTHING</tt> will be returned. The division uses {@link MathContext#DECIMAL128}
*
* @param other the operand to divide this by.
* @return an <tt>Amount</tt> representing the division of <tt>this</tt> by <tt>other</tt> or <tt>NOTHING</tt>
* if either of both is empty.
*/
@Nonnull
@CheckReturnValue
public Amount divideBy(@Nullable Amount other) {
if (other == null || other.isZeroOrNull() || isEmpty()) {
return NOTHING;
}
return Amount.of(value.divide(other.value, MathContext.DECIMAL128));
}
/**
* Returns the ratio in percent from <tt>this</tt> to <tt>other</tt>.
* This is equivalent to {@code this / other * 100}
*
* @param other the base to compute the percentage from.
* @return an <tt>Amount</tt> representing the ratio between <tt>this</tt> and <tt>other</tt>
* or <tt>NOTHING</tt> if either of both is empty.
*/
@Nonnull
@CheckReturnValue
public Amount percentageOf(@Nullable Amount other) {
return divideBy(other).toPercent();
}
/**
* Returns the increase in percent of <tt>this</tt> over <tt>other</tt>.
* This is equivalent to {@code ((this / other) - 1) * 100}
*
* @param other the base to compute the increase from.
* @return an <tt>Amount</tt> representing the percentage increase between <tt>this</tt> and <tt>other</tt>
* or <tt>NOTHING</tt> if either of both is empty.
*/
@Nonnull
@CheckReturnValue
public Amount percentageDifferenceOf(@Nonnull Amount other) {
return divideBy(other).subtract(ONE).toPercent();
}
/**
* Determines if the value is filled and equal to 0.00.
*
* @return <tt>true</tt> if this value is filled and equal to 0.00, <tt>false</tt> otherwise.
*/
public boolean isZero() {
return value != null && value.compareTo(BigDecimal.ZERO) == 0;
}
/**
* Determines if the value is filled and not equal to 0.00.
*
* @return <tt>true</tt> if this value is filled and not equal to 0.00, <tt>false</tt> otherwise.
*/
public boolean isNonZero() {
return value != null && value.compareTo(BigDecimal.ZERO) != 0;
}
/**
* Determines if the value is filled and greater than 0.00
*
* @return <tt>true</tt> if this value is filled and greater than 0.00, <tt>false</tt> otherwise.
*/
public boolean isPositive() {
return value != null && value.compareTo(BigDecimal.ZERO) > 0;
}
/**
* Determines if the value is filled and less than 0.00
*
* @return <tt>true</tt> if this value is filled and less than 0.00, <tt>false</tt> otherwise.
*/
public boolean isNegative() {
return value != null && value.compareTo(BigDecimal.ZERO) < 0;
}
/**
* Determines if the value is empty or equal to 0.00
*
* @return <tt>true</tt> if this value is empty, or equal to 0.00, <tt>false</tt> otherwise.
*/
public boolean isZeroOrNull() {
return value == null || value.compareTo(BigDecimal.ZERO) == 0;
}
/**
* Converts a given decimal fraction into a percent value i.e. 0.34 to 34 %.
* Effectively this is {@code this * 100}
*
* @return a percentage representation of the given decimal value.
*/
@Nonnull
@CheckReturnValue
public Amount toPercent() {
return this.times(ONE_HUNDRED);
}
/**
* Converts a percent value into a decimal fraction i.e. 34 % to 0.34
* Effectively this is {@code this / 100}
*
* @return a decimal representation fo the given percent value.
*/
@Nonnull
@CheckReturnValue
public Amount asDecimal() {
return divideBy(ONE_HUNDRED);
}
/**
* Compares this amount against the given one.
* <p>
* If both amounts are empty, they are considered equal, otherwise, if the given amount is empty, we consider this
* amount to be larger. Likewise, if this amount is empty, we consider the given one to be larger.
*
* @param o the amount to compare to
* @return 0 if both amounts are equal, -1 of this amount is less than the given one or 1 if this amount is greater
* than the given one
*/
@Override
@SuppressWarnings("squid:S1698")
@Explain("Indentity against this is safe and a shortcut to speed up comparisons")
public int compareTo(Amount o) {
if (o == null) {
return 1;
}
if (o == this) {
return 0;
}
if (o.value == null) {
return 1;
}
if (value == null) {
return -1;
}
return value.compareTo(o.value);
}
/**
* Determines if this amount is greater than the given one.
* <p>
* See {@link #compareTo(Amount)} for an explanation of how empty amounts are handled.
*
* @param o the other amount to compare against
* @return <tt>true</tt> if this amount is greater than the given one
*/
public boolean isGreaterThan(Amount o) {
return compareTo(o) > 0;
}
/**
* Determines if this amount is greater than or equal to the given one.
* <p>
* See {@link #compareTo(Amount)} for an explanation of how empty amounts are handled.
*
* @param o the other amount to compare against
* @return <tt>true</tt> if this amount is greater than or equals to the given one
*/
public boolean isGreaterThanOrEqual(Amount o) {
return compareTo(o) >= 0;
}
/**
* Determines if this amount is less than the given one.
* <p>
* See {@link #compareTo(Amount)} for an explanation of how empty amounts are handled.
*
* @param o the other amount to compare against
* @return <tt>true</tt> if this amount is less than the given one
*/
public boolean isLessThan(Amount o) {
return compareTo(o) < 0;
}
/**
* Determines if this amount is less than or equal to the given one.
* <p>
* See {@link #compareTo(Amount)} for an explanation of how empty amounts are handled.
*
* @param o the other amount to compare against
* @return <tt>true</tt> if this amount is less than or equals to the given one
*/
public boolean isLessThanOrEqual(Amount o) {
return compareTo(o) <= 0;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Amount otherAmount = (Amount) o;
if (this.value == null || otherAmount.value == null) {
return (this.value == null) == (otherAmount.value == null);
}
return this.value.compareTo(otherAmount.value) == 0;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
/**
* Compares this amount against the given amount and returns the one with the lower value.
* <p>
* If either of the amounts is empty, the filled one is returned. If both are empty, an empty amount is returned.
*
* @param other the amount to compare against
* @return the amount with the lower value or an empty amount, if both amounts are empty
*/
@Nonnull
@SuppressWarnings("squid:S1698")
@Explain("Indentity against this is safe and a shortcut to speed up comparisons")
public Amount min(@Nullable Amount other) {
if (other == this || other == null) {
return this;
}
if (isEmpty()) {
return other;
}
if (other.isEmpty()) {
return this;
}
return this.value.compareTo(other.value) < 0 ? this : other;
}
/**
* Compares this amount against the given amount and returns the one with the higher value.
* <p>
* If either of the amounts is empty, the filled one is returned. If both are empty, an empty amount is returned.
*
* @param other the amount to compare against
* @return the amount with the higher value or an empty amount, if both amounts are empty
*/
@Nonnull
@SuppressWarnings("squid:S1698")
@Explain("Indentity against this is safe and a shortcut to speed up comparisons")
public Amount max(@Nullable Amount other) {
if (other == this || other == null) {
return this;
}
if (isEmpty()) {
return other;
}
if (other.isEmpty()) {
return this;
}
return this.value.compareTo(other.value) > 0 ? this : other;
}
/**
* Negates <tt>this</tt> amount and returns the new amount.
*
* @return an <tt>Amount</tt> representing the negated <tt>Amount</tt>. If <tt>this</tt> is empty, <tt>NOTHING</tt>
* is returned.
*/
public Amount negate() {
return times(MINUS_ONE);
}
/**
* Returns a {@link Amount} whose value is {@code (this % other)}.
*
* @param other the divisor value by which this {@code Amount} is to be divided.
* @return an {@link Amount} representing the remainder of the two amounts
* @see BigDecimal#remainder(BigDecimal)
*/
public Amount remainder(Amount other) {
if (isEmpty() || other.isZeroOrNull()) {
return Amount.NOTHING;
}
return Amount.of(value.remainder(other.value));
}
@Override
public String toString() {
return toSmartRoundedString(NumberFormat.TWO_DECIMAL_PLACES).toString();
}
/**
* Formats the represented value as percentage. Up to two digits will be shown if non zero.
* Therefore <tt>12.34</tt> will be rendered as <tt>12.34 %</tt> but <tt>5.00</tt> will be
* rendered as <tt>5 %</tt>. If the value is empty, "" will be returned.
* <p>
* A custom {@link NumberFormat} can be used by directly calling {@link #toSmartRoundedString(NumberFormat)}
* or to disable smart rounding (to also show .00) {@link #toString(NumberFormat)} can be called using
* {@link NumberFormat#PERCENT}.
*
* @return a string representation of this number using {@code NumberFormat#PERCENT}
* or "" if the value is empty.
*/
public String toPercentString() {
return toSmartRoundedString(NumberFormat.PERCENT).toString();
}
/**
* Tries to convert the wrapped value to a roman numeral representation.
* Any fractional part of this {@code BigDecimal} will be discarded,
* and if the resulting "{@code BigInteger}" is too big to fit in an {@code int}, only the low-order 32 bits are
* returned.
*
* @return a string representation of this number as roman numeral or "" for values <= 0 and >= 4000.
*/
public String toRomanNumeralString() {
return RomanNumeral.toRoman(value.intValue());
}
/**
* Formats the represented value by rounding to zero decimal places. The rounding mode is obtained from
* {@link NumberFormat#NO_DECIMAL_PLACES}.
*
* @return a rounded representation of this number using {@code NumberFormat#NO_DECIMAL_PLACES}
* or "" is the value is empty.
*/
public String toRoundedString() {
return toSmartRoundedString(NumberFormat.NO_DECIMAL_PLACES).toString();
}
/**
* Rounds the number according to the given format. In contrast to only round values when displaying them as
* string, this method returns a modified <tt>Amount</tt> which as potentially lost some precision. Depending on
* the next computation this might return significantly different values in contrast to first performing all
* computations and round at the end when rendering the values as string.
* <p>
* The number of decimal places and the rounding mode is obtained from <tt>format</tt> ({@link NumberFormat}).
*
* @param format the format used to determine the precision of the rounding operation
* @return returns an <tt>Amount</tt> which is rounded using the given {@code NumberFormat}
* or <tt>NOTHING</tt> if the value is empty.
*/
@Nonnull
@CheckReturnValue
public Amount round(@Nonnull NumberFormat format) {
return round(format.getScale(), format.getRoundingMode());
}
/**
* Rounds the number according to the given format. In contrast to only round values when displaying them as
* string, this method returns a modified <tt>Amount</tt> which as potentially lost some precision. Depending on
* the next computation this might return significantly different values in contrast to first performing all
* computations and round at the end when rendering the values as string.
*
* @param scale the precision
* @param roundingMode the rounding operation
* @return returns an <tt>Amount</tt> which is rounded using the given {@code RoundingMode}
* or <tt>NOTHING</tt> if the value is empty.
*/
@Nonnull
@CheckReturnValue
public Amount round(int scale, @Nonnull RoundingMode roundingMode) {
if (isEmpty()) {
return NOTHING;
}
return Amount.ofRounded(value.setScale(scale, roundingMode));
}
private Value convertToString(NumberFormat format, boolean smartRound) {
if (isEmpty()) {
return Value.of(null);
}
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(smartRound ? 0 : format.getScale());
df.setMaximumFractionDigits(format.getScale());
df.setDecimalFormatSymbols(format.getDecimalFormatSymbols());
df.setGroupingUsed(format.isUseGrouping());
return Value.of(df.format(value)).append(" ", format.getSuffix());
}
/**
* Converts the number into a string according to the given <tt>format</tt>. The returned {@link Value} provides
* helpful methods to pre- or append texts like units or currency symbols while gracefully handling empty values.
*
* @param format the {@code NumberFormat} used to obtain the number of decimal places,
* the decimal format symbols and rounding mode
* @return a <tt>Value</tt> containing the string representation according to the given format
* or an empty <tt>Value</tt> if <tt>this</tt> is empty.
* @see Value#tryAppend(String, Object)
*/
@Nonnull
public Value toString(@Nonnull NumberFormat format) {
return convertToString(format, false);
}
/**
* Converts the number into a string just like {@link #toString(NumberFormat)}. However, if the number has no
* decimal places, a rounded value (without .00) will be returned.
*
* @param format the {@code NumberFormat} used to obtain the number of decimal places,
* the decimal format symbols and rounding mode
* @return a <tt>Value</tt> containing the string representation according to the given format
* or an empty <tt>Value</tt> if <tt>this</tt> is empty. Omits 0 as decimal places.
* @see #toString()
*/
@Nonnull
public Value toSmartRoundedString(@Nonnull NumberFormat format) {
return convertToString(format, true);
}
/**
* Creates a "scientific" representation of the amount.
* <p>
* This representation will shift the value in the range 0..999 and represent the decimal shift by a well
* known unit prefix. The following prefixes will be used:
* <ul>
* <li>f - femto</li>
* <li>n - nano</li>
* <li>u - micro</li>
* <li>m - milli</li>
* <li>K - kilo</li>
* <li>M - mega</li>
* <li>G - giga</li>
* </ul>
* <p>
* An input of <tt>0.0341 V</tt> will be represented as <tt>34.1 mV</tt> if digits was 4 or 34 mV is digits was 2
* or less.
*
* @param digits the number of decimal digits to display
* @param unit the unit to be appended to the generated string
* @return a scientific string representation of the amount.
*/
@Nonnull
public String toScientificString(int digits, String unit) {
if (isEmpty()) {
return "";
}
int metric = NEUTRAL_METRIC;
double doubleValue = this.value.doubleValue();
while (Math.abs(doubleValue) >= 990d && metric < METRICS.length - 1) {
doubleValue /= 1000d;
metric += 1;
}
int effectiveDigits = digits;
if (metric == NEUTRAL_METRIC) {
while (!Doubles.isZero(doubleValue) && Math.abs(doubleValue) < 1.01 && metric > 0) {
doubleValue *= 1000d;
metric -= 1;
// We loose accuracy, therefore we limit our decimal digits...
effectiveDigits -= 3;
}
}
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(Math.max(0, effectiveDigits));
df.setMaximumFractionDigits(Math.max(0, effectiveDigits));
df.setDecimalFormatSymbols(NLS.getDecimalFormatSymbols());
df.setGroupingUsed(true);
StringBuilder sb = new StringBuilder(df.format(doubleValue));
if (metric != NEUTRAL_METRIC) {
sb.append(" ");
sb.append(METRICS[metric]);
}
if (unit != null) {
sb.append(unit);
}
return sb.toString();
}
/**
* Provides a machine-readable representation of this amount.
*
* @return the amount formatted in a language independent matter and rounded to two decimal digits or an empty
* string if the underlying amount is empty
*/
public String toMachineString() {
if (isEmpty()) {
return "";
}
if (rounded) {
return getAmount().toString();
} else {
return round(2, RoundingMode.HALF_UP).getAmount().toString();
}
}
/**
* Returns the number of decimal digits (ignoring decimal places after the decimal separator).
*
* @return the number of digits required to represent this number. Returns 0 if the value is empty.
*/
public long getDigits() {
if (value == null) {
return 0;
}
return Math.round(Math.floor(Math.log10(value.doubleValue()) + 1));
}
private void throwExceptionIfEmpty() {
if (value == null) {
throw new IllegalStateException("The value is empty.");
}
}
}