How to format a number to include a "+/-" only when it is Not 0?

211 views Asked by At

I want to display double number with +/- sign and I am using this decimal format for that

double d = 0;
    DecimalFormat nf = new DecimalFormat("+#0.0;-#0.0");
    System.out.println(nf.format(d));

    d = -1;
    System.out.println(nf.format(d));

    d = 1;
    System.out.println(nf.format(d));

and I am getting out-put like this

+0.0
-1.0
+1.0

but I want 0.0 without + sign like

 0.0
-1.0
+1.0

Thanks

3

There are 3 answers

0
Sinkingpoint On BEST ANSWER

As with this, I'm not entirely sure there is a way to solve this with only decimal format, however a slight modification of the regex given in that answer (Again, Credit: @Bohemian) seems to solve the problem.

System.out.println(nf.format(d).replaceAll("^[-+](?=0(.0*)?$)", ""));

This simply looks for numbers in the format of the number 0 (i.e 0 followed by some number of zeros after a decimal point), removing the sign preceding it.

0
Piyush Bhattacharya On

If you search on this forum there already exists an answer to your question. The answer is available at https://stackoverflow.com/a/11929642/4284989

You cannot satisfy your requirement using format symbols alone. You will have to replace the sign symbol with "" (empty) after applying the format.

For clarity, the below snippet will give you your required answer.

public class FormatTester {
public static void main(String[] args){

DecimalFormat nf = new DecimalFormat("#,##0.0");
String formattedValue = nf.format(Double.parseDouble(args[0]));
formattedValue = formattedValue.replaceAll( "^-(?=0(.0*)?$)", "");

System.out.println(">>>> "+formattedValue+" <<<<");    
}
}
0
Peter Pan On

Maybe better and more simple code:

String style = d > 0 ? "+%.2f" : "% .2f";
System.out.println(String.format(style, d));