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?

1
  • What you meant by When I use to String Commented Jan 11, 2013 at 6:04

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.