Example of Java formatting a value into a currency format
- 2020-04-01 03:13:50
- OfStack
Format a value, such as 123456789.123, that you want to display as "$123,456,789.123. "to complete the requirement, you can format it using the java.text.numberformat class
The NumberFormat class provides encapsulation of numeric formats. In the JDK, you typically use a subclass of NumberFormt, java.text.decimalformat, to do this. The most common constructor for this class is:
Public DecimalFormat (String pattern)
Where, the parameter pattern represents the format string passed in
Code:
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class numberFormat
{
public static void main(String[] args)
{
NumberFormat nf = new DecimalFormat("$,###.##");
String testStr = nf.format(123456789.123);
System.out.println(testStr);
}
}
DecimalFormat features:
Accept the corresponding format string and format the parts of the value for display. # is for Arabic numerals
In the format string, parts such as $appear as they are, except for the ones that have a representative meaning