czerny
czerny

Reputation: 16664

Formatting numbers - grouping of decimal-place digits in Java

Does DecimalFormat class support grouping of decimal-place digits similar to it does for integer part of numbers through methods setGroupingUsed() and setGroupingSize?

I'd like number 123456.789012 to be formatted as 123,456.789,012.

Upvotes: 0

Views: 1543

Answers (2)

MarsAtomic
MarsAtomic

Reputation: 10673

According to the API guide:

The grouping separator is commonly used for thousands, but in some countries it separates ten-thousands. The grouping size is a constant number of digits between the grouping characters, such as 3 for 100,000,000 or 4 for 1,0000,0000. If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So "#,##,###,####" == "######,####" == "##,####,####".

This passage suggests that the grouping symbol can only be applied to the integer portion of the number. If we set a pattern like so:

String pattern = "###,###.###,###";

and pass it to an instance of DecimalFormat, the result is:

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

whereas the more typical:

String pattern = "###,###.###";

works as expected.

setGroupingUsed isn't applicable because it takes a boolean to indicate whether the number will be expressed with grouped digits. setGroupingSize isn't applicable either, because it only governs how many digits comprise each group.

The only way to get what you want is to roll your own formatter.

Addendum:

Cracking open the source of DecimalFormat reveals that the number to be formatted is divided into three sections: leftDigits, or the leftmost digits of the integer portion of the number, zeroDigits, or the rightmost digits of the integer portion of the number, and rightDigits, or the fractional portion of the number.

The code includes the following (comment starts at line 2507):

// The position of the last grouping character is
// recorded (should be somewhere within the first two blocks
// of characters)

By "blocks," the comment clearly refers to leftDigits and zeroDigits, so even the developers assumed that grouping digits would only occur in the integer portion and made no provisions for grouping on the fractional portion (aside from throwing an exception).

Upvotes: 3

Lovelin B
Lovelin B

Reputation: 110

There is no grouping after the decimal place. Such a format will be invalid and throw an exception.

Upvotes: 0

Related Questions