Convert Number to String to Number

Convert Number to String to Number

I got sometimes strange results, when i read a Double of a Java Method and display it in XPages as String. Especially with minus values…

I found the following function on http://dontpanic82.blogspot.com/2010/04/xpages-code-for-numberstring-conversion.html:

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);
        }
    }
}

Leave a Reply

comment-avatar

*