Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom formatted number with period and comma

Somewhat related to this question and several other SO questions relating to formatting decimals (all of which did not help me in this instance).

I am trying to format a Long into a String e.g. 123456 -> 012.345,6 (period followed by comma as strange as it may seem, it's a project requirement).

I am experimenting with DecimalFormat for the formatting:

private static final DecimalFormat format = new DecimalFormat("##0.000,0");

However it throws an exception during instantiation:

java.lang.IllegalArgumentException: Malformed pattern "##0.000,0"

I have also experimented with changing the locale to an EU system beforehand e.g.

NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.GERMAN);

How can I format numbers in this way? Is DecimalFormat the wrong solution? Can I use a NumberFormat? Or will I need a custom formatter?

like image 242
glenneroo Avatar asked Nov 18 '25 06:11

glenneroo


2 Answers

You should avoid constructing DecimalFormat directly. Commas are always used for grouping in the pattern definition, regardless of how they appear in the target locale. Similarly, periods are always used for decimals. This appears illogical, but one must remember this is a pattern definition, and like #, these characters describe a replacement, not the character itself.

NumberFormat f = NumberFormat.getInstance(Locale.GERMANY);
if (f instanceof DecimalFormat) {
    ((DecimalFormat) f).applyPattern("##0,000.0");
}
f.format(123456 / 10.0);

The division by 10 is necessary to obtain a digit after the decimal point.

like image 192
David Grant Avatar answered Nov 20 '25 19:11

David Grant


Sorry if I am missing your request, but if you need a non-standard number representation then you can write a formatter simply enough:

static String formatLong(long value) {
        String ret = Long.toString(value);

        // Make the value 7 digits by prepending 0's
        while(ret.length()<7) ret="0"+ret;

        // Add a comma before the last digit
        ret = ret.substring(0,ret.length()-1)+","+ret.substring(ret.length()-1);

        // Add a period before the 4th digit
        ret = ret.substring(0,ret.length()-5)+"."+ret.substring(ret.length()-5);

        return ret;
    }

long a = 123456;
System.out.println(formatLong(a));

Prints "012.345,6"

like image 25
ChrisCantrell Avatar answered Nov 20 '25 19:11

ChrisCantrell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!