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:20

You can try by using two different DecimalFormat objects based on the condition as follows:

double d=100;
double d2=100.5;
double d3=100.41;

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

if(d%1==0){ // this is to check a whole number
    DecimalFormat df2=new DecimalFormat("'$'");
    System.out.println(df2.format(d));
}

System.out.println(df.format(d2));
System.out.println(df.format(d3));

Output:-
$100
$100.50
$100.41
查看更多
\"骚年 ilove
3楼-- · 2019-02-07 18:24

You can check "is number whole or not" and choose needed number format.

public class test {

  public static void main(String[] args){
    System.out.println(function(100d));
    System.out.println(function(100.5d));
    System.out.println(function(100.42d));
  }

  public static String function(Double doubleValue){
    boolean isWholeNumber=(doubleValue == Math.round(doubleValue));
    DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.GERMAN);
    formatSymbols.setDecimalSeparator('.');

    String pattern= isWholeNumber ? "#.##" : "#.00";    
    DecimalFormat df = new DecimalFormat(pattern, formatSymbols);
    return df.format(doubleValue);
  }
}

will give exactly what you want:

100
100.50
100.42
查看更多
乱世女痞
4楼-- · 2019-02-07 18:24

I know its too late. However following worked for me :

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.UK);
new DecimalFormat("\u00A4#######0.00",otherSymbols).format(totalSale);

 \u00A4 : acts as a placeholder for currency symbol
 #######0.00 : acts as a placeholder pattern for actual number with 2 decimal 
 places precision.   

Hope this helps whoever reads this in future :)

查看更多
登录 后发表回答