Re: Decimal display for very large/small numbers
On Apr 2, 2:51 am, "Andrew Thompson via JavaKB.com" <u32984@uwe>
wrote:
Post an SSCCE, and I might provide some further
consideration.
Thanks for thinking about it, and for the URL. Although I should have
been, I wasn't familiar with SSCCE. Your suggestion that preparing an
SSCCE almost always helps in solving the problem was correct in this
case. I managed to answer my own question by going through the
exercise (after a weekend of frustration!). So, for the sake of
completeness, here's the correct code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.MathContext;
import java.text.DecimalFormat;
public class TestDecimals {
public TestDecimals() {
}
public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader buf_in = new BufferedReader(reader);
String read = "0"; //exit string (zero)
do {
int precision = 6; //User input
DecimalFormat decimals = new DecimalFormat();
Double dbl = null;
read = buf_in.readLine();
Double ddbl = dbl.parseDouble(read); //User input
BigDecimal convertValue = BigDecimal.valueOf(ddbl);
BigDecimal convertedResult = converter(ddbl);
decimals.setMaximumFractionDigits(precision);
decimals.setMinimumFractionDigits(precision);
if (convertedResult.doubleValue()>10E6 ||
convertedResult.doubleValue()<10E-6) {
BigDecimal bd = convertedResult.round(new
MathContext(precision + 1));
System.out.println("The result (MathContext adjusted)
is: " + bd);
} else {
System.out.println("The result (decimal format
adjusted) is: " + decimals.format(convertedResult).toString());
}
} while (!read.toLowerCase().equals("0"));
}
public static BigDecimal converter(Double testValue) {
if (testValue > 1000) {
BigDecimal result = new BigDecimal(testValue / 10E-6);
return result;
} else if (testValue < 0.0001) {
BigDecimal result = new BigDecimal(testValue / 10E6);
return result;
} else {
BigDecimal result = new BigDecimal(testValue);
return result;
}
}
}