SaneEconomy/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/NumberUtils.java

83 lines
2.3 KiB
Java
Raw Normal View History

package org.appledash.saneeconomy.utils;
2016-06-15 01:47:14 +02:00
import com.google.common.base.Strings;
import org.appledash.saneeconomy.economy.Currency;
2016-06-15 01:47:14 +02:00
2019-11-04 10:43:33 +01:00
import java.math.BigDecimal;
import java.text.DecimalFormat;
2016-07-29 13:49:41 +02:00
import java.text.NumberFormat;
import java.text.ParseException;
/**
* Created by AppleDash on 6/14/2016.
* Blackjack is still best pony.
*/
2019-11-04 18:25:17 +01:00
public final class NumberUtils {
2019-11-04 10:43:33 +01:00
private static final BigDecimal INVALID_DOUBLE = BigDecimal.ONE.negate();
2016-06-15 01:47:14 +02:00
2019-11-04 18:25:17 +01:00
private NumberUtils() {
}
2019-11-04 10:43:33 +01:00
public static BigDecimal parsePositiveDouble(String sDouble) {
if (Strings.isNullOrEmpty(sDouble)) {
return INVALID_DOUBLE;
}
2016-06-15 01:47:14 +02:00
sDouble = sDouble.trim();
2016-06-15 01:47:14 +02:00
if (sDouble.equalsIgnoreCase("nan") || sDouble.equalsIgnoreCase("infinity") || sDouble.equalsIgnoreCase("-infinity")) {
return INVALID_DOUBLE;
}
2016-07-29 13:49:41 +02:00
2019-11-04 10:43:33 +01:00
BigDecimal doub;
try {
2019-11-04 10:43:33 +01:00
doub = (BigDecimal) constructDecimalFormat().parseObject(sDouble);
} catch (ParseException | NumberFormatException e) {
return INVALID_DOUBLE;
}
2019-11-04 10:43:33 +01:00
if (doub.compareTo(BigDecimal.ZERO) < 0) {
return INVALID_DOUBLE;
}
2019-11-04 10:43:33 +01:00
/*if (Double.isInfinite(doub) || Double.isNaN(doub)) {
2016-10-02 18:06:04 +02:00
return INVALID_DOUBLE;
2019-11-04 10:43:33 +01:00
}*/
2016-10-02 18:06:04 +02:00
return doub;
}
2016-06-15 01:47:14 +02:00
2019-11-04 10:43:33 +01:00
public static BigDecimal filterAmount(Currency currency, BigDecimal amount) {
2016-07-29 13:49:41 +02:00
try {
2019-11-04 10:43:33 +01:00
return (BigDecimal) constructDecimalFormat().parse(currency.getFormat().format(amount.abs()));
2016-07-29 13:49:41 +02:00
} catch (ParseException e) {
throw new NumberFormatException();
}
2016-06-15 01:47:14 +02:00
}
2019-11-04 10:43:33 +01:00
public static BigDecimal parseAndFilter(Currency currency, String sDouble) {
return filterAmount(currency, parsePositiveDouble(sDouble));
2016-06-15 01:47:14 +02:00
}
2019-11-04 10:43:33 +01:00
public static boolean equals(BigDecimal left, BigDecimal right) {
if (left == null) {
throw new NullPointerException("left == null");
}
if (right == null) {
throw new NullPointerException("right == null");
}
return left.compareTo(right) == 0;
}
2019-11-04 10:43:33 +01:00
private static DecimalFormat constructDecimalFormat() {
DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance();
decimalFormat.setParseBigDecimal(true);
return decimalFormat;
}
}