Java String.format with currency symbol

前端 未结 5 1858
广开言路
广开言路 2021-01-07 23:18

There is some existing code of the follow form which is used for format numerical values:

String.format( pattern, value )

5条回答
  •  爱一瞬间的悲伤
    2021-01-07 23:45

    No need to reinvent the wheel. DecimalFormat comes with currency support:

    String output = DecimalFormat.getCurrencyInstance().format(123.45);
    

    This also comes with full locale support by optionally passing in a Locale:

    String output = DecimalFormat.getCurrencyInstance(Locale.GERMANY).format( 123.45);
    

    Here's a test:

    System.out.println(DecimalFormat.getCurrencyInstance().format( 123.45) );
    System.out.println(DecimalFormat.getCurrencyInstance(Locale.GERMANY).format( 123.45)) ;
    

    Output:

    $123.45
    123,45 €
    

提交回复
热议问题