jodd.typeconverter.impl.DoubleConverter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jodd-core Show documentation
Show all versions of jodd-core Show documentation
Jodd Core tools and utilities, including type converters, JDateTime, cache etc.
// Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.
package jodd.typeconverter.impl;
import jodd.typeconverter.TypeConversionException;
import jodd.typeconverter.TypeConverter;
import jodd.util.StringUtil;
/**
* Converts given object to Double
.
* Conversion rules:
*
* null
value is returned as null
* - object of destination type is simply casted
* - object is converted to string, trimmed, and then converted if possible.
*
* Number string may start with plus and minus sign.
*/
public class DoubleConverter implements TypeConverter {
public Double convert(Object value) {
if (value == null) {
return null;
}
if (value.getClass() == Double.class) {
return (Double) value;
}
if (value instanceof Number) {
return Double.valueOf(((Number)value).doubleValue());
}
try {
String stringValue = value.toString().trim();
if (StringUtil.startsWithChar(stringValue, '+')) {
stringValue = stringValue.substring(1);
}
return Double.valueOf(stringValue);
} catch (NumberFormatException nfex) {
throw new TypeConversionException(value, nfex);
}
}
}