Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double to String, how to delete 0 after dot [duplicate]

Tags:

java

android

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?

like image 595
Ivan Avatar asked Nov 30 '22 22:11

Ivan


2 Answers

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.

like image 174
Heinzi Avatar answered Dec 09 '22 13:12

Heinzi


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

like image 21
Bhavesh Patadiya Avatar answered Dec 09 '22 14:12

Bhavesh Patadiya