I am using BigDecimal to round an input based on desired significant figures, actual input and desired significant figures comes from a JtextPane. This is the sample code;
String input = "1234.56";
String sf = "3";
String ans;
BigDecimal decRep = new BigDecimal(Double.parseDouble(input));
decRep = decRep.round(new MathContext(Integer.parseInt(sf)));
ans = String.valueOf(decRep.doubleValue());
System.out.println(ans);
This will result to 1230.0
which is well and fine. But it also required to output if it rounded down or if it rounded up.
Is there a way to determine so?
If I understand your question correctly, you want to find out whether a value was rounded up or down in respect to its original value. This would be the easiest way to do that:
public BigDecimal roundAndLog(String input, String sigFigs) {
BigDecimal decimal = new BigDecimal(input);
BigDecimal decimalRounded = decimal.round(new MathContext(Integer.parseInt(sigFigs)));
int compared = decimalRounded.compareTo(decimal);
if (compared == -1) {
System.out.println("Rounded down!");
} else if (compared == 0) {
System.out.println("Value didn't change!");
} else {
System.out.println("Rounded up!");
}
return decimalRounded;
}