001/* 002 * Licensed under the Apache License, Version 2.0 (the "License"); 003 * you may not use this file except in compliance with the License. 004 * You may obtain a copy of the License at 005 * 006 * http://www.apache.org/licenses/LICENSE-2.0 007 * 008 * Unless required by applicable law or agreed to in writing, software 009 * distributed under the License is distributed on an "AS IS" BASIS, 010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 011 * See the License for the specific language governing permissions and 012 * limitations under the License. 013 */ 014package org.gbif.common.parsers; 015 016import java.text.DecimalFormat; 017import java.text.NumberFormat; 018import java.text.ParsePosition; 019import java.util.Locale; 020 021import org.apache.commons.lang3.StringUtils; 022 023/** 024 * Utils class to parse numbers trying various locales so that dots and comma based formats are both supported. 025 * All methods swallow exceptions and return null instead. 026 */ 027public class NumberParser { 028 029 private NumberParser() { 030 031 } 032 033 public static Double parseDouble(String x) { 034 final String trimmed = x == null ? null : x.trim(); 035 if (StringUtils.isEmpty(trimmed)) return null; 036 037 try { 038 return Double.parseDouble(x); 039 } catch (NumberFormatException e) { 040 NumberFormat format = DecimalFormat.getInstance(Locale.GERMANY); 041 ParsePosition pos = new ParsePosition(0); 042 // verify that the parsed position is at the end of the string! 043 Number num = format.parse(trimmed, pos); 044 if (num != null && trimmed.length() == pos.getIndex()) { 045 return num.doubleValue(); 046 } 047 } 048 return null; 049 } 050 051 public static Integer parseInteger(String x) { 052 final String trimmed = x == null ? null : x.trim(); 053 if (StringUtils.isEmpty(trimmed)) return null; 054 055 try { 056 return Integer.parseInt(x); 057 } catch (NumberFormatException e) { 058 NumberFormat format = DecimalFormat.getInstance(Locale.GERMANY); 059 ParsePosition pos = new ParsePosition(0); 060 // verify that the parsed position is at the end of the string! 061 Number num = format.parse(trimmed, pos); 062 if (num != null && trimmed.length() == pos.getIndex()) { 063 return num.intValue(); 064 } 065 } 066 return null; 067 } 068}