Formatting Number to Currency and Percentage Strings Thursday, April 18, 2013

I found we can use: java.text.DecimalFormat, to take a number like a Integer or a BigDecimal and format it to a string, with the desired formatting:

import java.text.DecimalFormat

def num1 = 654572 //java.lang.Integer
def num2 = 0.7507577625 //java.math.BigDecimal
//println "num1: " + num1.getClass()
//println "num2: " + num2.getClass()

println "Format Currency:"
def list = [0, 1, 6, 23, 245, 8765, 92309, 654572, 6.57, 23.23, 5.876, 5.875, 5.874 ]
list.each{ value ->
    def pattern = "\$##,###.##"
    def moneyform = new DecimalFormat(pattern)
    String output = moneyform.format(value)
    println(value + " " + pattern + " " + output)
}

println "Format Percentage:"
def list1 = [ 0.7507577625, 1.0423815336, 1.1714391045, 0.8603150483 ]
list1.each{ value ->
    def pattern1 = "###.##%"
    def percentform = new DecimalFormat(pattern1)
    String output1 = percentform.format(value)
    println(value + " " + pattern1 + " " + output1)
}
Output:

Format Currency:
0 $##,###.## $0
1 $##,###.## $1
6 $##,###.## $6
23 $##,###.## $23
245 $##,###.## $245
8765 $##,###.## $8,765
92309 $##,###.## $92,309
654572 $##,###.## $654,572
6.57 $##,###.## $6.57
23.23 $##,###.## $23.23
5.876 $##,###.## $5.88
5.875 $##,###.## $5.88
5.874 $##,###.## $5.87

Format Percentage:
0.7507577625 ###.##% 75.08%
1.0423815336 ###.##% 104.24%
1.1714391045 ###.##% 117.14%
0.8603150483 ###.##% 86.03%

Java Tutorial: Decimal Formatting

0 comments: