Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not displaying decimals if double is a whole number?

I am making a graphical calculator program in Java and have a method that performs an operation based on user input, and returns a double to be displayed in a JTextField. However, I would like the result to be displayed as a whole number, without a following ".0" where there are no significant digits after the decimal point, but still display decimal points when necessary. What's the most efficient way of doing this?

like image 497
Zero Avatar asked Nov 02 '12 18:11

Zero


People also ask

How do you check if a double value has no decimal part?

Compare two values: the normal double, and the double after floor ing it. If they are the same value, there is no decimal component.

How do you show decimals that are not whole numbers?

Go to Conditional Formatting > New rule from home ribbon. Select rule type as “Use a formula…” Check if there is a value after decimal point using a formula like =Mod(A1,1)>0. Click the format button.


1 Answers

You can use DecimalFormat for suppressing the trailing characters, e.g.:

DecimalFormat format = new DecimalFormat("#.##");
double doubleFromTextField = Double.parseDouble(myField.getText());
System.out.println(format.format(doubleFromTextField));
like image 73
Reimeus Avatar answered Sep 22 '22 04:09

Reimeus