I'm writing some rows to a text file using groovy (grails 1.3.7) and I want to format the currency like this example output:
$100,000,000.00
$9,123,123.25
$10.20
$1,907.23
So basically right-justified, or left padded, with the dollar sign in front of the number so they all line up like the above. The first number is the longest we would expect to see. Right now I have an amount variable that is simply defined with a def and not string or number or anything specific like that but I can obviously change that if need be. Thanks!
You probably want to use NumberFormat.getCurrencyInstance()
. This will return a NumberFormat
object that uses the standard currency representation for your default Locale (or optionally, the one you pass in).
To right justify, you can use String.padLeft()
.
Example:
def formatter = java.text.NumberFormat.currencyInstance
def values = [0, 100000000, 9123123.25, 10.20, 1907.23]
def formatted = values.collect { formatter.format(it) }
def maxLen = formatted*.length().max()
println formatted.collect { it.padLeft(maxLen) }.join("\n")
//output
$0.00
$100,000,000.00
$9,123,123.25
$10.20
$1,907.23
In grails soemthing like this will format it nicely with comma separators.
<g:formatNumber number="${150000}" type="currency" currencyCode="USD"/>
For right aligning I would use style:
<td style='text-align:right;...'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With