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

前端 未结 10 618
旧巷少年郎
旧巷少年郎 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:30

    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

提交回复
热议问题