Groovy货币格式 [英] Groovy currency formatting

查看:47
本文介绍了Groovy货币格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用groovy(grails 1.3.7)将一些行写入文本文件,并且我想像以下示例输出一样格式化货币:

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

所以基本上是右对齐的或左填充的,数字前面有美元符号,因此它们都像上面那样排列.第一个数字是我们期望看到的最长的数字.现在我有一个用def定义的数量变量,而不是字符串或数字或类似的东西,但是如果需要的话,我显然可以更改它.谢谢!

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().

示例:

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

这篇关于Groovy货币格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆