Home > Software engineering >  Can I achieved to convert double to String and remove all trailing zero behind the point value?
Can I achieved to convert double to String and remove all trailing zero behind the point value?

Time:12-28

I have looking for the solution around and doing a little workaround here, but can not wrap up all to meet my expectations. For example I have double value as below

double x = 101.00000
double y = 102.02000
double z = 103.20000
double k = 104.30020

I want all the value to become String with the smallest number of decimal they have to show. Expected result

String l = "101"
String m = "102.02"
String n = "103.2"
String o = "104.3002"
// and the l = formatted x, m = formatted y, n = formatted z, o = formatted k

can this be achieved in any way?

Thank you

(Note: someone have suggest my question may duplicate with remove trailing zero in java. But I suggest it's different because in my question the base value is double not String)

CodePudding user response:

Hope this helps:

public static String format(double val) {
     if(val == (long)val) 
          return String.format("%d", (long) val);
     else
          return String.format("%s", val);
}

Input:

1. 101.00000
2. 102.02000

Output:

1. 101
2. 102.02

CodePudding user response:

CONVERT DOUBLE TO STRING

In Java, if you want to convert a value type to another, you should see this 'another type' class and try to find a converting method.

I this case you want to convert a Double type to String. String class has a method called String.valueOf(double d) that changes the number value to String. It also can convert other number types to String thanks to the overload properties.


REMOVING UNNECESSARY ZERO

Once you have the String values, use this code with each one to remove the unnecessary zeros.

s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");

In your case:

Double x = 101.00000;
Double y = 102.02000;
Double z = 103.20000;
Double k = 104.30020;

String l = String.valueOf(x);
String m = String.valueOf(y);
String n = String.valueOf(z);
String o = String.valueOf(k);

l = l.indexOf(".") < 0 ? l : l.replaceAll("0*$", "").replaceAll("\\.$", "");
m = m.indexOf(".") < 0 ? m : m.replaceAll("0*$", "").replaceAll("\\.$", "");
n = n.indexOf(".") < 0 ? n : n.replaceAll("0*$", "").replaceAll("\\.$", "");
o = o.indexOf(".") < 0 ? o : o.replaceAll("0*$", "").replaceAll("\\.$", "");

Output:

  • 101
  • 102.02
  • 103.2
  • 104.3002
  • Related