Stewart Clay Stewart Clay - 1 month ago 11
Java Question

can not round numbers

I am making a calculator but i am struggling to make my numbers round off such as 18.0 to 18. How do i display a number as 18 and not 18.0 for my calculator? Here is the code i am using.

String answer;
double D;
secondnumber = Double.parseDouble(numTx.getText());

if (operation.equals("+")) {
result = firstnum + secondnumber;
answer = Double.toString(result);
numTx.setText(answer);
}
if (operation.equals("-")) {
result = firstnum - secondnumber;
answer = Double.toString(result);
numTx.setText(answer);
}
if (operation.equals("/")) {
result = firstnum / secondnumber;
answer = Double.toString(result);
numTx.setText(answer);
}
if (operation.equals("*")) {
result = firstnum * secondnumber;
answer = Double.toString(result);
numTx.setText(answer);
}


code that i tried using but it gave huge errors.
answer = String.format("%1$.1f", result);

Answer

Outputting a double value as 18 instead of 18.0 is not rounding. That's formatting.

Use a NumberFormat and specify the minimum and maximum number of digits you want to see after the decimal point.

Easiest way to create such a NumberFormat is to actually create a DecimalFormat.

Example:

DecimalFormat fmt = new DecimalFormat("0.####"); // show between 0 and 4 decimals, as needed
System.out.println(fmt.format(18.0));    // prints: 18
System.out.println(fmt.format(18.250));  // prints: 18.25
System.out.println(fmt.format(Math.PI)); // prints: 3.1416
Comments