FloatFormatter.java
01 /*
02  * Copyright 2008-2016 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.text.DecimalFormat;
20 import java.text.NumberFormat;
21 
22 import static griffon.util.GriffonNameUtils.isBlank;
23 
24 /**
25  @author Andres Almiray
26  @since 2.0.0
27  */
28 public class FloatFormatter extends AbstractFormatter<Float> {
29     public static final String PATTERN_CURRENCY = "currency";
30     public static final String PATTERN_PERCENT = "percent";
31 
32     private final NumberFormat numberFormat;
33 
34     public FloatFormatter() {
35         this(null);
36     }
37 
38     public FloatFormatter(@Nullable String pattern) {
39         if (isBlank(pattern)) {
40             numberFormat = new DecimalFormat("#.0");
41         else if (PATTERN_CURRENCY.equalsIgnoreCase(pattern)) {
42             numberFormat = NumberFormat.getCurrencyInstance();
43         else if (PATTERN_PERCENT.equalsIgnoreCase(pattern)) {
44             numberFormat = NumberFormat.getPercentInstance();
45         else {
46             numberFormat = new DecimalFormat(pattern);
47         }
48     }
49 
50     @Nullable
51     public String format(@Nullable Float number) {
52         return number == null null : numberFormat.format(number);
53     }
54 
55     @Nullable
56     @Override
57     public Float parse(@Nullable String strthrows ParseException {
58         if (isBlank(str)) return null;
59         try {
60             return numberFormat.parse(str).floatValue();
61         catch (java.text.ParseException e) {
62             throw new ParseException(e);
63         }
64     }
65 }