How to use Java's DecimalFormat for “smart” cu

2019-02-07 17:49发布

I'd like to use Java's DecimalFormat to format doubles like so:

#1 - 100 -> $100
#2 - 100.5 -> $100.50
#3 - 100.41 -> $100.41

The best I can come up with so far is:

new DecimalFormat("'$'0.##");

But this doesn't work for case #2, and instead outputs "$100.5"

Edit:

A lot of these answers are only considering cases #2 and #3 and not realizing that their solution will cause #1 to format 100 as "$100.00" instead of just "$100".

9条回答
爷、活的狠高调
2楼-- · 2019-02-07 18:10

You can use the following format:

DecimalFormat dformat = new DecimalFormat("$#.##");

查看更多
戒情不戒烟
3楼-- · 2019-02-07 18:11

Does it have to use DecimalFormat?

If not, it looks like the following should work:

String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber);
//Handle the weird exception of formatting whole dollar amounts with no decimal
currencyString = currencyString.replaceAll("\\.00", "");
查看更多
女痞
4楼-- · 2019-02-07 18:13

printf also works.

Example:

double anyNumber = 100; printf("The value is %4.2f ", anyNumber);

Output:

The value is 100.00

4.2 means force the number to have two digits after the decimal. The 4 controls how many digits to the right of the decimal.

查看更多
一纸荒年 Trace。
5楼-- · 2019-02-07 18:16

Try using

DecimalFormat.setMinimumFractionDigits(2);
DecimalFormat.setMaximumFractionDigits(2);
查看更多
Summer. ? 凉城
6楼-- · 2019-02-07 18:18

Try

new DecimalFormat("'$'0.00");

Edit:

I Tried

DecimalFormat d = new DecimalFormat("'$'0.00");

        System.out.println(d.format(100));
        System.out.println(d.format(100.5));
        System.out.println(d.format(100.41));

and got

$100.00
$100.50
$100.41
查看更多
Emotional °昔
7楼-- · 2019-02-07 18:19

Use NumberFormat:

NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 
double doublePayment = 100.13;
String s = n.format(doublePayment);
System.out.println(s);

Also, don't use doubles to represent exact values. If you're using currency values in something like a Monte Carlo method (where the values aren't exact anyways), double is preferred.

See also: Write Java programs to calculate and format currency

查看更多
登录 后发表回答