4

Possible Duplicate:
How to nicely format floating types to String?

I have number:

Double d1=(Double)0;
Double d2=(Double)2.2;
Double d3=(Double)4;

When I use to String, I get 0.0, 2.2, 4.0, but I want to see 0, 2.2, 4. How can I do it?

Community
  • 1
  • 1
Ivan
  • 191
  • 1
  • 2
  • 11

2 Answers2

18

Use DecimalFormat.format insted of Double.toString:

Double d1 = (Double)0.0;
Double d2 = (Double)2.2;
Double d3 = (Double)4.0;

// Example: Use four decimal places, but only if required
NumberFormat nf = new DecimalFormat("#.####");

String s1 = nf.format(d1); // 0
String s2 = nf.format(d2); // 2.2
String s3 = nf.format(d3); // 4

You don't even need Doubles for that, doubles will work just fine.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

First Convert your Double to String with String.valueof(YOUR_VARIABLE)

then Use Below Function to do it.

private String getyourNumber(String NUMBER) {
    if(!NUMBER.contains(".")) {
        return NUMBER;
    }

    return NUMBER.replaceAll(".?0*$", "");
}

then Convert your

String to Double with Double.parseDouble(YOUR_RETURNED_STRING).

Bhavesh Patadiya
  • 25,740
  • 15
  • 81
  • 107