Home » Android » java – Show decimal of a double only when needed

# java – Show decimal of a double only when needed

Questions:

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”?

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.

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

Don’t use doubles. You can lose some precision. Here’s a general purpose function.

public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}

You can call it with

round(yourNumber, 3, BigDecimal.ROUND_HALF_UP);

“precision” being the number of decimal points you desire.

Copy from Here.