Wednesday, December 31, 2008

convert String like 123,444.00 with comma to double

// First, check whether the String is valid integer

/**
* Valid if string is valid number
* 12345.55
* 12,345.55
*
* @param pValue
* @return
*/
public static boolean isValidNumber(String pValue) {
if (!isSet(pValue)) {
return false;
}

try {
NumberFormat nfDLocal = NumberFormat.getNumberInstance();
ParsePosition ppos = new ParsePosition(0);
nfDLocal.parse(pValue, ppos);

if (ppos.getIndex() == pValue.length()) {
return true;
}
else {
return false;
}
}
catch (Throwable e) {
return false;
}
}

// Seconde.
/**
* Convert string to double, make sure call isValidNumber first before calling this method
* @param pValue
* @return
*/
public static double toDouble(String pValue) {
NumberFormat nfDLocal = NumberFormat.getNumberInstance();
ParsePosition ppos = new ParsePosition(0);
Number num = nfDLocal.parse(pValue, ppos);

return num.doubleValue();
}

No comments:

Post a Comment