DEV Community

Cover image for Formatting Currency in Java
Edwin Torres
Edwin Torres

Posted on • Edited on

1

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.

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.