Search code examples
javastringspring-bootdoublenumber-formatting

How to convert double to String and remove all trailing zero behind the point value?


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

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


Solution

  • 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