01 /*
02 * Copyright 2008-2014 the original author or authors.
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 * http://www.apache.org/licenses/LICENSE-2.0
09 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package griffon.core.formatters;
17
18 import javax.annotation.Nullable;
19 import java.math.BigDecimal;
20 import java.math.BigInteger;
21 import java.text.DecimalFormat;
22 import java.text.NumberFormat;
23
24 import static griffon.util.GriffonNameUtils.isBlank;
25
26 /**
27 * @author Andres Almiray
28 * @since 2.0.0
29 */
30 public class BigIntegerFormatter extends AbstractFormatter<BigInteger> {
31 public static final String PATTERN_CURRENCY = "currency";
32 public static final String PATTERN_PERCENT = "percent";
33
34 private final NumberFormat numberFormat;
35
36 public BigIntegerFormatter() {
37 this(null);
38 }
39
40 public BigIntegerFormatter(@Nullable String pattern) {
41 if (isBlank(pattern)) {
42 numberFormat = NumberFormat.getIntegerInstance();
43 } else if (PATTERN_CURRENCY.equalsIgnoreCase(pattern)) {
44 numberFormat = NumberFormat.getCurrencyInstance();
45 } else if (PATTERN_PERCENT.equalsIgnoreCase(pattern)) {
46 numberFormat = NumberFormat.getPercentInstance();
47 } else {
48 numberFormat = new DecimalFormat(pattern);
49 numberFormat.setParseIntegerOnly(true);
50 ((DecimalFormat) numberFormat).setParseBigDecimal(true);
51 }
52 }
53
54 @Nullable
55 public String format(@Nullable BigInteger number) {
56 return number == null ? null : numberFormat.format(number);
57 }
58
59 @Nullable
60 @Override
61 public BigInteger parse(@Nullable String str) throws ParseException {
62 if (isBlank(str)) return null;
63 try {
64 Number number = numberFormat.parse(str);
65 if (number instanceof BigDecimal) {
66 return ((BigDecimal) number).toBigInteger();
67 }
68 return BigInteger.valueOf(number.longValue());
69 } catch (java.text.ParseException e) {
70 throw new ParseException(e);
71 }
72 }
73 }
|