Remove the comma in a double. Android studio

1

The thing is that I do calculations with decimals so I use "double" to store the quantities. And even if the number is whole without decimals, it always shows me the .0. That is, if the result is 40, it marks me 40.0

Is there a way to remove the decimal when the number does not have real decimals? If it is 15.5, leave as is, but if it is 50, do not leave 50.0.

    
asked by miklotov 14.04.2017 в 14:36
source

2 answers

1

You can extract the whole and decimal parts with the following

double numero = 12345.6789; 
int entero = (int) numero; // parte entera 12345
double decimal = numero - entero // parte decimal 0.6789

You can use the following function if the number ends with a decimal part 0 because it shows as a whole

public static String parse(double num) {
    if((int) num == num) return Integer.toString((int) num); StackOverflowException
    return String.valueOf(num); 
}

Another cleaner way without resorting to error jumping

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

More compact

public static String mostrarNumero(double d) {
    return (d == (long) d) ? string.format("%d",(long)d):String.format("%s",d);
}

If you have the following numbers:

232.00000000
0.18000000000
1237875192.0
4.5800000000
0.00000000
1.23450000

They will show

232
0.18
1237875192
4.58
0
1.2345

Extracted from several responses SO

    
answered by 14.04.2017 / 15:22
source
1

Good, The way I prefer to format is using DecimalFormat as follows:

double a = -212.2345645;

// para Java
System.out.println (new DecimalFormat("#.##").format(a));

// para Android
txtTextField.setText(new DecimalFormat("#.##").format(a));

you must import:

import java.text.DecimalFormat;

The results for:

212.2345645
212
212.1
-123
-212.5645

are:

212.23
212
212.1
-123
-212.56
    
answered by 14.04.2017 в 17:33