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
%s refers to a string data type, %f refers to a float data type, and %d refers to a double data type.
"%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.
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.
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 €
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With