26 March 2010

Parsing a String decimal number into a Double (using locale)

Valid since: op4j 1.0

Description
Obtaining a Double object from a String containing a decimal number written in a locale-specific manner.

Scenario
We have a String variable called value which contains a decimal number written by a Frenchman:
// value == "34,59"
French use the comma sign (",") as a decimal separator, contrary to most English-speaking people and also contrary to the standard way to represent numbers as Strings in Java (which is American English). We will need a locale-sensitive conversion then.


Recipe
Use a version of the FnString.toDouble(...) function that allows a locale to be specified:

Double value =
    Op.on(strValue).exec(FnString.toDouble("fr")).get();


Comments
op4j's number conversion functions come in many flavours, including specifying locales, scales and rounding modes for Integer, Longs, BigDecimals, Doubles, etc.

Equivalent non-op4j Java code:
NumberFormat numberFormat = 
    NumberFormat.getInstance(new Locale("fr"));
Double value = (Double) numberFormat.parse(strValue);

No comments:

Post a Comment