Arran
Arran

Reputation: 157

How do I comma separate zero padded String.format doubles in java?

I am trying to use String.format for get comma separated, zero padded doubles. I am using:

"%0,9.2f", unitPrice

Unit price is a double. When unitPrice is, for example, 44.99 I get 000044.99 when I want 00,044.99. If unit price is 4499 instead I get 04,499.00 as wanted.

Upvotes: 2

Views: 1130

Answers (2)

gustf
gustf

Reputation: 2017

This is only possible for values equal or larger than 1000. Checked the source code of Java 8 and the zero padding is done after inserting group separators.

You have to write your own format like the answer from @Elliot Frisch.

Note that his answer is Locale dependent, but you can force the comma , by providing a localized instance of DecimalFormatSymbols.

new DecimalFormat("00,000.00", DecimalFormatSymbols.getInstance(Locale.US))

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201537

You could use a DecimalFormat (a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits) like

DecimalFormat df = new DecimalFormat("00,000.00");
System.out.println(df.format(44.99));
System.out.println(df.format(4499));

Output is (as requested)

00,044.99
04,499.00

Upvotes: 3

Related Questions