forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberFormatters.java
More file actions
69 lines (51 loc) · 2.15 KB
/
NumberFormatters.java
File metadata and controls
69 lines (51 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package modern.challenge;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.NumberFormat.Style;
import java.text.ParseException;
import java.util.Locale;
public final class NumberFormatters {
private NumberFormatters() {
throw new AssertionError("Cannot be instantiated");
}
public static String forLocale(Locale locale, double number) {
return format(locale, Style.SHORT, null, number);
}
public static String forLocaleStyle(Locale locale, Style style, double number) {
return format(locale, style, null, number);
}
public static String forLocaleStyleRound(Locale locale, Style style, RoundingMode mode, double number) {
return format(locale, style, mode, number);
}
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 String format(Locale locale, Style style, RoundingMode mode, double number) {
if (locale == null || style == null) {
return String.valueOf(number); // or use a default format
}
NumberFormat nf = NumberFormat.getCompactNumberInstance(locale, style);
if (mode != null) {
nf.setRoundingMode(mode);
}
return nf.format(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);
}
}