Numeric Input

Number Display

Displaying numbers in an application depends to a great degree on context. Although you should always use NumberFormat or its equivivalent to get locally formatted numbers, the exact format you get can and should be tailored to the application's needs.

Here are some of the formats:

As you can see, number formats are one of the reasons you'll want to test software in some non-English locales.

Use at least two locales with divergent formats as a baseline. For example, the French number format features a non-breaking space as the grouping separator, as well as the common European use of comma as a decimal separator, while Japanese is similar to the US English format.

Hindi demonstrates numeric shaping in action. There are more than 20 complete sets of digits in Unicode, most of which are not Latin (1, 2, 3) digits. Java can parse these for you and, since JDK 1.4, NumberFormat can do "numeric shaping" on a locale-sensitive basis.

Input

Input of numbers is trickier than it looks. The basic NumberFormat.parse method will suffice in most cases, but you should be aware of common input mistakes and other issues inherent in relying on NumberFormat. For one thing, NumberFormat returns a value with no error when it fails to recognize the next character in the input string. This means you have to check the ParsePosition to see if the whole string was devoured or not (see French parsing below)

There are a variety of other things that can confuse NumberFormat. These include:

The hard test cases involve floating point values. You have to be careful of NumberFormat trimming off the decimal portion of the number (so that 1.3 becomes 1.0) by checking ParsePosition. This is a lot more work in code than the default parse() method.

webMethods code sometimes uses a more aggressive parser, com.wm.g11n.text.NumberUtils, that handles many of these cases. Note that the results you get are highly locale dependent.

The select box below feeds both classes. Values with pp= indicate the position where a ParseException was thrown. Compare the results you get with some of these inputs:

Demo

Locale:

String to Parse:

Uploading Files