Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

USD Currency Formatting in Java

In Java, how can I efficiently convert floats like 1234.56 and similar BigDecimals into Strings like $1,234.56

I'm looking for the following:

String 12345.67 becomes String $12,345.67

I'm also looking to do this with Float and BigDecimal as well.

like image 403
Tidbtis Avatar asked Jun 19 '10 14:06

Tidbtis


People also ask

What is %d and %s in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

What is %- 5d in Java?

"%5d" Format a string with the required number of integers and also pad with spaces to the left side if integers are not adequate. "%05d" Format a string with the required number of integers and also pad with zeroes to the left if integers are not adequate.

How do you display currency format?

Tip: You can also press Ctrl+1 to open the Format Cells dialog box. In the Format Cells dialog box, in the Category list, click Currency or Accounting. In the Symbol box, click the currency symbol that you want. Note: If you want to display a monetary value without a currency symbol, you can click None.


2 Answers

There's a locale-sensitive idiom that works well:

import java.text.NumberFormat;

// Get a currency formatter for the current locale.
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println(fmt.format(120.00));

If your current locale is in the US, the println will print $120.00

Another example:

import java.text.NumberFormat;
import java.util.Locale;

Locale locale = new Locale("en", "UK");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
System.out.println(fmt.format(120.00));

This will print: £120.00

like image 127
Brian Clapper Avatar answered Oct 14 '22 19:10

Brian Clapper


DecimalFormat moneyFormat = new DecimalFormat("$0.00");
System.out.println(moneyFormat.format(1234.56));
like image 33
krock Avatar answered Oct 14 '22 20:10

krock