001/* 002 * Copyright 2002-2012 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.format.number; 018 019import java.text.NumberFormat; 020import java.text.ParseException; 021import java.text.ParsePosition; 022import java.util.Locale; 023 024import org.springframework.format.Formatter; 025 026/** 027 * Abstract formatter for Numbers, 028 * providing a {@link #getNumberFormat(java.util.Locale)} template method. 029 * 030 * @author Juergen Hoeller 031 * @author Keith Donald 032 * @since 3.0 033 */ 034public abstract class AbstractNumberFormatter implements Formatter<Number> { 035 036 private boolean lenient = false; 037 038 039 /** 040 * Specify whether or not parsing is to be lenient. Default is false. 041 * <p>With lenient parsing, the parser may allow inputs that do not precisely match the format. 042 * With strict parsing, inputs must match the format exactly. 043 */ 044 public void setLenient(boolean lenient) { 045 this.lenient = lenient; 046 } 047 048 049 @Override 050 public String print(Number number, Locale locale) { 051 return getNumberFormat(locale).format(number); 052 } 053 054 @Override 055 public Number parse(String text, Locale locale) throws ParseException { 056 NumberFormat format = getNumberFormat(locale); 057 ParsePosition position = new ParsePosition(0); 058 Number number = format.parse(text, position); 059 if (position.getErrorIndex() != -1) { 060 throw new ParseException(text, position.getIndex()); 061 } 062 if (!this.lenient) { 063 if (text.length() != position.getIndex()) { 064 // indicates a part of the string that was not parsed 065 throw new ParseException(text, position.getIndex()); 066 } 067 } 068 return number; 069 } 070 071 /** 072 * Obtain a concrete NumberFormat for the specified locale. 073 * @param locale the current locale 074 * @return the NumberFormat instance (never {@code null}) 075 */ 076 protected abstract NumberFormat getNumberFormat(Locale locale); 077 078}