Formatting Currency in Java

An easy way to output currency in Java is to use the built-in NumberFormat class. This lets you format a number like 1000.2399 for output as $1,000.24.

NumberFormat rounds to two decimals, adds necessary commas, and includes a $ in front.

To use NumberFormat, import the class at the top of your program:

import java.text.NumberFormat;

Enter fullscreen mode Exit fullscreen mode

Next, create the NumberFormat object and assign it to a variable formatter:

NumberFormat formatter = NumberFormat.getCurrencyInstance();

Enter fullscreen mode Exit fullscreen mode

Finally, use the formatter object to invoke the format() method on the amount to be formatted:

double amt = 1000.2399;
String amtFormatted = formatter.format(amt);

Enter fullscreen mode Exit fullscreen mode

Note that the result is a String value.

Here is a full program example:

import java.text.NumberFormat;

public class NumberFormatExample {
  public static void main(String[] args) {
    NumberFormat formatter = NumberFormat.getCurrencyInstance();

    double amt = 1000.2399;
    String amtFormatted = formatter.format(amt);

    System.out.println("original: " + amt);
    System.out.println("formatted: " + amtFormatted);
  }
}

Enter fullscreen mode Exit fullscreen mode

Here is the output:

original:    1000.2399
formatted:   $1,000.24

Enter fullscreen mode Exit fullscreen mode

Follow me on Twitter @realEdwinTorres for more programming tips and help.

原文链接:Formatting Currency in Java

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容