I am making a calculator for a project,using Swing but I am finding one task particulary hard because it is something I have not yet learned. So for this calculator I need a rounding menu I have a list of menu items 0 through to 9 which stipulate the rounding precision to be applied to all calculations. I have taken a screen shot to give you an idea.
I am not sure how to do this, online I have found many people mention the BigDecimal class and one of the instructors told me to search for the round method, however I am looking at both of these options but I am not sure how to implement them.
I thought I would ask if any one had any similar code samples I could look at.

All 3 Replies

there are:

1/ basic and strong Assembler's rounding mode

``````int baseInt = (doubleNumber + (0.05))/100
double roundedNumber = baseInt * 100``````

2/ rounding problems if NumberValue ends with 3,6,9, sometimes (lots of decimal places) I never check why, never solved, just ignored, compared with outPut/rounding from MsExcel

``````int decimalPlace = 0;
BigDecimal bd = new BigDecimal(doubleNumber);
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
doubleNumber = bd.doubleValue();``````

3/ excelent and strong way, but required that by usage JFormattedTextField and proper/correct way

``````amountFormat = NumberFormat.getNumberInstance();
amountFormat.setMinimumFractionDigits(2);
amountFormat.setMaximumFractionDigits(2);
amountFormat.setRoundingMode(RoundingMode.HALF_UP);``````

4/ excelent and strong way

``````public class round {

public static double roundTo2Places(double value) {
assert value >= Long.MIN_VALUE / 100 && value <= Long.MAX_VALUE / 100;
long digits = (long) (value < 0 ? value * 100 - 0.5 : value * 100 + 0.5);
return (double) digits / 100;
}

private round() {
}
}``````

- your GUI isn't layed corect way, please don't use bound/size etc
- JTextFields knows Font
- JComponets aren't justified
- JTextField.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);

<my view>
I don't like that, I think it's ugly
</my view>

sure there are exists another way "How to Rounding Correctly"

Thank you for the examples I think I can go ahead now.
I was hoping you could elaborate on your ending comments as I am not sure what they mean:

- JTextFields knows Font
- JComponets aren't justified
- JTextField.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);

input TextField replace with JFormattedTextField#NumberInstance