Wednesday, April 28, 2010

XPages: Code snippet for number/string conversion

The DecimalFormat object is cached in the application scope due to performance/memory concerns.

The default locale for the conversion seems to be the locale of the OS on the server, so if you want to support multiple locales, you'd have to extend the functionality.

Example usage (Norwegian locale):
String to number
NumberConverter.stringToNumber( '15,55', '0.00' ) -> java.lang.Double

Number to string
NumberConverter.numberToString( 15.926, '0.00' ) -> "15,93"

var NumberConverter = {
stringToNumber : function(numberString, patternString) {
try {
if( !numberString ){ return null; }

var formatter = NumberConverter.getFormatter(patternString);
return formatter.parse(numberString);
} catch( e ){ Debug.logException( e ); }
},
numberToString : function(number, patternString) {
try {
if( !number ){ return null; }

number = new java.lang.Double(number);
var formatter = NumberConverter.getFormatter(patternString);
return formatter.format(number);
} catch( e ){ Debug.logException( e ); }
},
getFormatter : function(patternString) {
try {
var cacheKey = 'numberFormatter' + patternString;
var numberFormatter = applicationScope[cacheKey];
if(!numberFormatter) {
numberFormatter = java.text.DecimalFormat(patternString);
applicationScope[cacheKey] = numberFormatter;
}

return numberFormatter;
} catch( e ){ Debug.logException( e ); }
}
}

2 comments:

Mark Hughes said...

Great post as always, i really enjoy you sharing of techniques.

Tommy Valand said...

Thank you. :)