Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy currency formatting

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!

like image 775
tnichol Avatar asked Jan 09 '14 22:01

tnichol


2 Answers

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
like image 198
ataylor Avatar answered Nov 07 '22 23:11

ataylor


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;...'>
like image 33
user3155388 Avatar answered Nov 07 '22 22:11

user3155388