What I'm trying to accomplish is to get the code to format the number according to these rules:
If number is integer smaller than 10^6 or bigger than 10^-6, write it as integer, else write it in scientific format, rounded to 8 decimal places at most.
If number is decimal smaller than 10^6 or bigger than 10^-6, write it as decimal with 8 decimal places at most, else write it in scientific format, rounded to 8 places at most.
I got this code, but it doesn't work as it should:
BigDecimal upperLimit = BigDecimal.valueOf(1000000);
BigDecimal lowerLimit = BigDecimal.valueOf(0.000001);
BigDecimal bigNum = BigDecimal.valueOf(result);
String string = bigNum.toString();
if (bigNum.scale() <= 0) {
if (bigNum.compareTo(upperLimit) < 0 && bigNum.compareTo(lowerLimit) > 0) {
BigInteger integer = bigNum.toBigInteger();
string = integer.toString();
}
else {
int index = string.indexOf('0');
if (index < 8) {
string = format(bigNum, index - 2);
}
else {
string = format(bigNum, 8);
}
}
}
else {
if (bigNum.compareTo(upperLimit) < 0 && bigNum.compareTo(lowerLimit) > 0) {
string = bigNum.toString();
int index = string.indexOf('.');
string = string.substring(index, 8);
}
else {
string = format(bigNum, 8);
}
}
private static String format (BigDecimal x, int scale) {
NumberFormat formatter = new DecimalFormat("0.0E0");
formatter.setRoundingMode(RoundingMode.HALF_UP);
formatter.setMinimumFractionDigits(scale);
return formatter.format(x);
}
here is what it outputs:
input 123*2 (246) -> output 246 ✓
input 123.2*2 (246.4) -> crash
input 132.2*100000000 -> output 1.32200000e10 ✓
input 13222*10000 -> output 1.3e8 (should be 1.3222e8)
So as you can see, small integers are formatted well, but other types aren't. How to fix this and where is the problem, because I can't seem to find any?
Thank you for helping with this code.
NOTE: anyone can use this code for anything he needs once it's fixed.
Aucun commentaire:
Enregistrer un commentaire