Reputation: 21
I am making a calculator in Java where I can only display up to 17 characters so .
is considered as a character and E15
is considered 3 characters.
I have researched extensively on this site but could not a find a question like this... (sorry if there is a duplicate)
How can I force say a large BigDecimal like 9999998990000001
to something like 9.999998990000E15
.
I do not want it to be in scientific always so numbers say less than 16 characters long should not be in scientific notation.
Essentially like a handheld calculator if you are having trouble understanding.
Upvotes: 2
Views: 214
Reputation: 993
You could simply check if the numbers is less than 16 characters if not just do:
private static String formatNumber(BigDecimal bDecimal, int scaleInt) {
NumberFormat nFromatter = new DecimalFormat("0.0E0");
nFromatter.setRoundingMode(RoundingMode.HALF_UP);
nFromatter.setMinimumFractionDigits(scaleInt);
return formatter.format(bDecimal);
}
System.out.println(formatNumber(new BigDecimal("0.00001"), 2));
// Output will be 1.00E-5
System.out.println(formatNumber(new BigDecimal("0.00001"), 3));
// Output will be 1.000E-5
Upvotes: 2