BigDecimalFormatter.java
01 /*
02  * Copyright 2008-2015 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.text.DecimalFormat;
21 import java.text.NumberFormat;
22 
23 import static griffon.util.GriffonNameUtils.isBlank;
24 
25 /**
26  @author Andres Almiray
27  @since 2.0.0
28  */
29 public class BigDecimalFormatter extends AbstractFormatter<BigDecimal> {
30     public static final String PATTERN_CURRENCY = "currency";
31     public static final String PATTERN_PERCENT = "percent";
32 
33     private final NumberFormat numberFormat;
34 
35     public BigDecimalFormatter() {
36         this(null);
37     }
38 
39     public BigDecimalFormatter(@Nullable String pattern) {
40         if (isBlank(pattern)) {
41             numberFormat = new DecimalFormat();
42             ((DecimalFormatnumberFormat).setParseBigDecimal(true);
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             ((DecimalFormatnumberFormat).setParseBigDecimal(true);
50         }
51     }
52 
53     @Nullable
54     public String format(@Nullable BigDecimal number) {
55         return number == null null : numberFormat.format(number);
56     }
57 
58     @Nullable
59     @Override
60     public BigDecimal parse(@Nullable String strthrows ParseException {
61         if (isBlank(str)) return null;
62         try {
63             Number number = numberFormat.parse(str);
64             if (number instanceof BigDecimal) {
65                 return (BigDecimalnumber;
66             }
67             return new BigDecimal(number.longValue());
68         catch (java.text.ParseException e) {
69             throw new ParseException(e);
70         }
71     }
72 }