Java Currency Format -1234.34 to -$1,234

Question: How to format currency. Example: -1234.34 to -$1,234

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

public class CurrencyTest {

	public static void main(String[] test) {
		double currency = -1234;
		NumberFormat dollarFormatter;
		dollarFormatter = NumberFormat.getCurrencyInstance(Locale.US);

		if (dollarFormatter instanceof DecimalFormat) {
			((DecimalFormat) dollarFormatter).setMaximumFractionDigits(0);
			((DecimalFormat) dollarFormatter).setNegativePrefix("-$");
			((DecimalFormat) dollarFormatter).setNegativeSuffix("");
		}

		String text = dollarFormatter.format(currency);
		System.out.println(text);
	}
}

Input: -1234.34
Output: -$1,234

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s