How to use Java's DecimalFormat for “smart” currency formatting?

前端 未结 10 662
旧巷少年郎
旧巷少年郎 2021-01-01 09:34

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

Th

10条回答
  •  没有蜡笔的小新
    2021-01-01 10: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
    

提交回复
热议问题