Parsing

Parsing is the reverse process of formatting. We have a given string and try to parse it as a number. This can be accomplished via the NumberFormat.parse() method. By default, parsing doesn't take advantage of grouping (for example, without grouping, 5,50 K is parsed as 5; with grouping, 5,50 K is parsed as 550000).

If we condense this information into a set of helper methods, then we obtain the following output:

public static Number parseLocale(Locale locale, String number) 
throws ParseException {

return parse(locale, Style.SHORT, false, number);
}

public static Number parseLocaleStyle(
Locale locale, Style style, String number) throws ParseException {

return parse(locale, style, false, number);
}

public static Number parseLocaleStyleRound(
Locale locale, Style style, boolean grouping, String number)
throws ParseException {

return parse(locale, style, grouping, number);
}

private static Number parse(
Locale locale, Style style, boolean grouping, String number)
throws ParseException {

if (locale == null || style == null || number == null) {
throw new IllegalArgumentException(
"Locale/style/number cannot be null");
}

NumberFormat nf = NumberFormat.getCompactNumberInstance(locale,
style);
nf.setGroupingUsed(grouping);

return nf.parse(number);
}

Let's parse 5K and 5 thousand into 5000 without explicit grouping:

// 5000
NumberFormatters.parseLocaleStyle(Locale.US, Style.SHORT, "5K");

// 5000
NumberFormatters.parseLocaleStyle(Locale.US, Style.LONG, "5 thousand");

Now, let's parse 5,50K and 5,50 thousand to 550000 with explicit grouping:

// 550000
NumberFormatters.parseLocaleStyleRound(
Locale.US, Style.SHORT, true, "5,50K");

// 550000
NumberFormatters.parseLocaleStyleRound(
Locale.US, Style.LONG, true, "5,50 thousand");

More tuning can be obtained via the setCurrency​(), setParseIntegerOnly(), setMaximumIntegerDigits(), setMinimumIntegerDigits(), setMinimumFractionDigits(), and setMaximumFractionDigits() methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.200.3