Skip to content

Commit

Permalink
#1170: add safe convertion from decimal to long in NumberUtils.
Browse files Browse the repository at this point in the history
  • Loading branch information
sbernard31 committed Dec 3, 2021
1 parent f7421bc commit af9a163
Showing 1 changed file with 14 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*******************************************************************************/
package org.eclipse.leshan.core.util.datatype;

import java.math.BigDecimal;
import java.math.BigInteger;

import com.upokecenter.numbers.EInteger;
Expand Down Expand Up @@ -45,7 +46,19 @@ public static Long numberToLong(Number number) throws IllegalStateException {
}

// handle FLOATING-POINT
// TODO should we support a safe floating-point conversion
BigDecimal bigDec = null;
if (number instanceof Float || number instanceof Double) {
bigDec = new BigDecimal(number.doubleValue());
} else if (number instanceof BigDecimal) {
bigDec = (BigDecimal) number;
}
if (bigDec != null) {
try {
return bigDec.longValueExact();
} catch (ArithmeticException e) {
throw new IllegalStateException(String.format("%s : can not be store in a long", bigDec));
}
}

// handle UNSIGNED
if (number instanceof ULong) {
Expand Down

0 comments on commit af9a163

Please sign in to comment.