Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String.format with currency symbol

Tags:

java

locale

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

String.format( pattern, value )

Note that I cannot change the code itself - I can only change the format pattern supplied to the code.

What is the format pattern to output a currency symbol for the default locale? Essentially, I want to achieve the following output:

String.format( "...", 123 )  => $ 123
like image 351
Marc Polizzi Avatar asked May 31 '12 02:05

Marc Polizzi


People also ask

What is %d and %s in Java?

%s refers to a string data type, %f refers to a float data type, and %d refers to a double data type.

What is %- 5d in Java?

"%5d" Format a string with the required number of integers and also pad with spaces to the left side if integers are not adequate. "%05d" Format a string with the required number of integers and also pad with zeroes to the left if integers are not adequate.

What is %s in Java?

the %s is a 'format character', indicating "insert a string here". The extra parameters after the string in your two function calls are the values to fill into the format character placeholders: In the first example, %s will be replaced with the contents of the command variable.


1 Answers

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 €
like image 186
Bohemian Avatar answered Oct 05 '22 12:10

Bohemian