Infinitiy NumberFormatException when creating BigDecimal
I have a function that formats a float value into USD currency format, but when the values are fractions of a dollar they get formatted to the last two non-zero decimals.
public static String currency(float number) {
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
currencyFormatter.setCurrency(Currency.getInstance("USD"));
String[] floatParts = new BigDecimal(number).toPlainString().split("\\.");
if(number < 1 && floatParts.length == 2) {
String decimalPortion = floatParts[1];
int numDecimalPlaces = 0;
while (decimalPortion.charAt(numDecimalPlaces) == '0')
numDecimalPlaces++;
if(numDecimalPlaces > 2)
currencyFormatter.setMaximumFractionDigits(numDecimalPlaces + 2);
else
currencyFormatter.setMaximumFractionDigits(2);
} else {
currencyFormatter.setMaximumFractionDigits(2);
}
return currencyFormatter.format(number);
}
I'm using Firebase Crashlytics and I'm getting this exception:
java.lang.NumberFormatException, Infinity or NaN: Infinity, exception at:
String[] floatParts = new BigDecimal(number).toPlainString().split("\\.");
What is causing this excpetion? If a non-numerical value was passed to this function, wouldn't the exception occur prior to reaching this line of code?
EDIT
The calling method:
@SerializedName("current_price")
@Expose
@ColumnInfo(name = "current_price")
private float currentPrice;
public void setCurrentPrice(float currentPrice) {
if(currentPrice < 0.0001) {
priceName = "$" + NumberFormatter.roundToLastDecimalDigits(currentPrice, 3);
} else {
priceName = NumberFormatter.currency(currentPrice);
}
this.currentPrice = currentPrice;
}
Comments
Post a Comment