Currency Formatting with getCurrencyInstance()

One of my normal practices is to strip all the formatting from a site value, simulate the site calculations, then compare my calculated value to the site value and display the results in the log file. But without formatting, the results can be hard to read as they go scrolling by. To add the formatting back is a relatively simply process. We can use the NumberFormat package and the format option to put the $ and , where they belong. Thus, 16384 becomes $16,384.

To use the formatting, import the following libraries, which sets the formatting based on locale.

import java.text.NumberFormat
import java.util.Locale

Next, create reference to the NumberFormat library:

NumberFormat defaultFormat = NumberFormat.getCurrencyInstance()

Finally, format the number back to a dollar figure:

log.logWarning(‘Total amount in dollars is:’ + defaultFormat.format(totalAmount))

One thing to note, the value to format must be an integer, float, double or big decimal value. Basically, anything other than a string.

As a basic example:

import com.kms.katalon.core.logging.KeywordLogger as KeywordLogger

import java.text.NumberFormat

import java.util.Locale

KeywordLogger log = new KeywordLogger()

NumberFormat defaultFormat = NumberFormat.getCurrencyInstance()

double dollarFigure = 16384.526;

log.logWarning(“The dollar figure is: ” + defaultFormat.format(dollarFigure))

Output:

The dollar figure is: $16,384.53

This space for rent.

Author Signature for Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.