Skip to content

Commit 93318d2

Browse files
awalter17ctrueden
authored andcommitted
Added asBigDecimal and asBigInteger methods
1 parent 601ece4 commit 93318d2

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/main/java/org/scijava/util/NumberUtils.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@
3131

3232
package org.scijava.util;
3333

34+
import java.math.BigDecimal;
35+
import java.math.BigInteger;
36+
3437

3538
/**
3639
* Useful methods for working with {@link Number} objects.
@@ -53,6 +56,21 @@ public static Number toNumber(final Object value, final Class<?> type) {
5356
return num == null ? null : ConversionUtils.cast(num, Number.class);
5457
}
5558

59+
public static BigDecimal asBigDecimal(final Number n) {
60+
// Using .doubleValue on a long or BigInteger would cause loss of accuracy
61+
if(BigInteger.class.isInstance(n)){
62+
return new BigDecimal((BigInteger) n);
63+
}
64+
else if(Long.class.isInstance(n)){
65+
return new BigDecimal(n.longValue());
66+
}
67+
return new BigDecimal(n.doubleValue());
68+
}
69+
70+
public static BigInteger asBigInteger(final Number n) {
71+
return BigInteger.valueOf(n.longValue());
72+
}
73+
5674
public static Number getMinimumNumber(final Class<?> type) {
5775
if (ClassUtils.isByte(type)) return Byte.MIN_VALUE;
5876
if (ClassUtils.isShort(type)) return Short.MIN_VALUE;

0 commit comments

Comments
 (0)