Negative sign in case of zero in java
I think this would be a workaround to avoid -0.0
. Use following code :
DecimalFormat df = new DecimalFormat("#,##0.0");
df.setRoundingMode(RoundingMode.HALF_UP);
df.setNegativePrefix(""); // set negative prefix BLANK
String formattedValue = df.format(-0.023);
df.setNegativePrefix("-"); // set back to - again
System.out.println(formattedValue);
Output :
0.0
I don't think there's a way of doing it just with DecimalFormat
, but this one-liner takes care of the problem:
formattedValue = formattedValue.replaceAll( "^-(?=0(\\.0*)?$)", "");
It removes (replaces with ""
) the minus sign if it's followed by 0-n characters of "0.00000..."
, so this will work for any similar result such as "-0"
, "-0."
or "-0.000000000"
Here's some test code:
public static void main(String[] args) {
System.out.println(format(-0.023));
System.out.println(format(12.123));
System.out.println(format(-12.345));
System.out.println(format(-0.123));
System.out.println(format(-1.777));
}
public static String format(double number) {
DecimalFormat df = new DecimalFormat("#,##0.0");
df.setRoundingMode(RoundingMode.HALF_UP);
String formattedValue = df.format(number);
formattedValue = formattedValue.replaceAll("^-(?=0(\\.0*)?$)", "");
return formattedValue;
}
Output (as expected):
0.0
12.1
-12.3
-0.1
-1.8
Try this: DecimalFormat df = new DecimalFormat("#,##0.0#;(#,##0.0#)");
According to the Javadoc for DecimalFormat:
A DecimalFormat pattern contains a positive and negative subpattern, for example, "#,##0.00;(#,##0.00)". Each subpattern has a prefix, numeric part, and suffix. The negative subpattern is optional; if absent, then the positive subpattern prefixed with the localized minus sign ('-' in most locales) is used as the negative subpattern. That is, "0.00" alone is equivalent to "0.00;-0.00". If there is an explicit negative subpattern, it serves only to specify the negative prefix and suffix; the number of digits, minimal digits, and other characteristics are all the same as the positive pattern. That means that "#,##0.0#;(#)" produces precisely the same behavior as "#,##0.0#;(#,##0.0#)".
That by check if the calculated value = "-0.0" make it equal "0.0"
and you can capsulate the code sush as
public String getFormattedValue(String input) {
DecimalFormat df = new DecimalFormat("#,##0.0");
df.setRoundingMode(RoundingMode.HALF_UP);
String formattedValue = df.format(input);
if (formattedValue.equalsIgnoreCase("-0.0")) {
formattedValue = "0.0";
}
System.out.println(formattedValue);
return formattedValue;
}