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

Thanks for reading you majestic sausage.

Author Signature for Posts

0