Groovy currency formatting

I am writing several lines to a text file using groovy (grails 1.3.7), and I want to format the currency, as in this example:

$100,000,000.00
  $9,123,123.25
         $10.20
      $1,907.23

Thus, in principle, on the right or left, with a dollar sign in front of the number, so they all line up as shown above. The first number is the longest that we expect to see. Right now I have a quantity variable that is simply defined using def, not a string or a number or something like that, but I can obviously change that if necessary. Thank you

+4
source share
2 answers

, NumberFormat.getCurrencyInstance(). NumberFormat, Locale (, , , ).

, String.padLeft().

:

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
+10

grails soemthing, , .

<g:formatNumber number="${150000}" type="currency" currencyCode="USD"/>

:

<td style='text-align:right;...'>
+4

All Articles