27 March 2010

Parsing a String number into a BigDecimal (no matter the decimal separator)

Valid since: op4j 1.0

Parsing a String containing a decimal number, without having to specify the symbol (comma or point) that has been used as a decimal separator.

A form on a web page allows users to input a decimal number. We have two of these numbers in String variables strValue1 and strValue2, and we want to parse these strings into java.math.BigDecimal objects.

But these two numbers have been input by users coming from different countries, and they have used their own different ways of specifying the decimal separator:
// strValue1 == "871,21"
// strValue2 == "421.441"

The FnString.toDouble(...) function provides the means of specifying the decimal point being used by using the DecimalPoint enum, one of which values allows both point and comma:

Double value1 =
Double value2 =

This method can also be used for obtaining Double or Float objects.

Also, note that this method will not work correctly if thousands separators are used, like in "1,423,243.87", because if decimal separators are not used but thousands separators are (like "1,423,243"), the system will not be able of determining which was the decimal separator being used.

No comments:

Post a Comment