Search code examples
javanumberformatter

Java Number format how to change +/- sign to custom text


I would like to use number formatting for adding a text different when number is positive or negative

ex :

-3.5 => (down) 3.5

+3.5 => (up) 3.5

I have found things in DecimalFormatSymbols, but it's only possible to change minus sign and only for a single char

Is there any other simple way using number formater?

DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale);
unusualSymbols.setDecimalSeparator('|');
unusualSymbols.setGroupingSeparator('^');
unusualSymbols.setMinusSign();
String strange = "#,##0.###";
DecimalFormat weirdFormatter =
        new DecimalFormat(strange, unusualSymbols);
weirdFormatter.setGroupingSize(4);

String bizarre = weirdFormatter.format(12345.678);
System.out.println(bizarre);

Solution

  • You can do this in your format string for DecimalFormat:

    (up) #,##0.###;(down) #,##0.###
    

    The linked doc contains a complete syntax definition for the format string, which starts:

    Pattern:
             PositivePattern
             PositivePattern ; NegativePattern
    

    This indicates that an optional second format string separated by a semicolon (;) will be used for negative values.

    Reading further:

    PositivePattern:
            Prefix_opt Number Suffix_opt
    NegativePattern:
            Prefix_opt Number Suffix_opt
    Prefix:
            any Unicode characters except \uFFFE, \uFFFF, and special characters
    Suffix:
            any Unicode characters except \uFFFE, \uFFFF, and special characters
    

    Each pattern (positive and negative) consists of a number format string (Number) with an optional prefix and suffix string. These additional parts can be any string you like (including (up) and (down)).