Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show decimal of a double only when needed

I got this problem with double (decimals).
When a double = 1.234567 Then I use String.format("%.3f", myString);
So the result is 1.234

But when my double is 10
The result will be 10,000
I want this to be 10

Is their a way to say that he only needs to show the decimals when it is "usefull"?

I saw some posts about this, but that was php or c#, couldn't find something for android/java about this (maybe I don't look good).

Hope you guys can help me out with this.

Edit, for now I use something like this: myString.replace(",000", "");
But I think their is a more "friendly" code for this.

like image 501
Bigflow Avatar asked Aug 06 '12 10:08

Bigflow


People also ask

How do you double only show two decimal places?

format(“%. 2f”) We also can use String formater %2f to round the double to 2 decimal places. However, we can't configure the rounding mode in String.

How many decimal places is a double?

The number of decimal places in a double is 16.

How do I show only 2 digits after a decimal in HTML?

parseFloat(num). toFixed(2);


1 Answers

The DecimalFormat with the # parameter is the way to go:

public static void main(String[] args) {          double d1 = 1.234567;         double d2 = 2;         NumberFormat nf = new DecimalFormat("##.###");         System.out.println(nf.format(d1));         System.out.println(nf.format(d2));     } 

Will result in

1.235 2 
like image 145
jolivier Avatar answered Oct 14 '22 19:10

jolivier