2 * Copyright 2000-2018 Vaadin Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
17 package com.vaadin.v7.data.util.converter;
19 import java.text.NumberFormat;
20 import java.text.ParsePosition;
21 import java.util.Locale;
24 * A converter that converts from the number type T to {@link String} and back.
25 * Uses the given locale and {@link NumberFormat} for formatting and parsing.
26 * Automatically trims the input string, removing any leading and trailing white
29 * Override and overwrite {@link #getFormat(Locale)} to use a different format.
36 public abstract class AbstractStringToNumberConverter<T>
37 implements Converter<String, T> {
40 * Returns the format used by {@link #convertToPresentation(Object, Locale)}
41 * and {@link #convertToModel(Object, Locale)}.
45 * @return A NumberFormat instance
48 protected NumberFormat getFormat(Locale locale) {
50 locale = Locale.getDefault();
53 return NumberFormat.getNumberInstance(locale);
57 * Convert the value to a Number using the given locale and
58 * {@link #getFormat(Locale)}.
61 * The value to convert
63 * The locale to use for conversion
64 * @return The converted value
65 * @throws ConversionException
66 * If there was a problem converting the value
69 protected Number convertToNumber(String value,
70 Class<? extends Number> targetType, Locale locale)
71 throws ConversionException {
76 // Remove leading and trailing white space
79 // Parse and detect errors. If the full string was not used, it is
81 ParsePosition parsePosition = new ParsePosition(0);
82 Number parsedValue = getFormat(locale).parse(value, parsePosition);
83 if (parsePosition.getIndex() != value.length()) {
84 throw new ConversionException("Could not convert '" + value
85 + "' to " + getModelType().getName());
88 if (parsedValue == null) {
100 * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang
101 * .Object, java.util.Locale)
104 public String convertToPresentation(T value,
105 Class<? extends String> targetType, Locale locale)
106 throws ConversionException {
111 return getFormat(locale).format(value);
117 * @see com.vaadin.data.util.converter.Converter#getPresentationType()
120 public Class<String> getPresentationType() {