概述
<code>DecimalFormat</code> is a concrete subclass of <code>NumberFormat</code> that formats decimal numbers.
It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits.
It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123).
All of these can be localized.
DecimalFormat 是NumberFormat的一个具体子类,为了格式化 十进制数;
支持不同的数字:整数、小数、百分数、科学计数、货币...;
<p>To obtain a <code>NumberFormat</code> for a specific locale, including the default locale, call one of <code>NumberFormat</code>'s factory methods, such as <code>getInstance()</code>.
In general, do not call the <code>DecimalFormat</code> constructors directly, since the <code>NumberFormat</code> factory methods may return subclasses other than <code>DecimalFormat</code>.
If you need to customize the format object, do something like this:
要获得特定区域的 NumberFormat实例,推荐使用NumberFormat的工厂方法getInstance();
不要直接调用 DecimalFormat的构造函数;
<blockquote><pre> NumberFormat f = NumberFormat.getInstance(loc); if (f instanceof DecimalFormat) { ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true); } </pre></blockquote>
A <code>DecimalFormat</code> comprises a <em>pattern</em> and a set of <em>symbols</em>. DecimalFormat包含一个pattern 和 一组符号;
The pattern may be set directly using <code>applyPattern()</code>, or indirectly using the API methods. pattern可以使用applyPattern() 或 API设置;
The symbols are stored in a <code>DecimalFormatSymbols</code> object. 符号被存储在 DecimalFormatSymbols中;
When using the <code>NumberFormat</code> factory methods, the pattern and symbols are read from localized <code>ResourceBundle</code>s.
- 在模式字符串中,
#
表示可选的数字,0
表示必须的数字。 ,
用作分组分隔符。.
用作小数点。¤
表示货币符号,其实际显示取决于默认的地区设置。%
表示百分比。
示例
DecimalFormat decimalFormat = new DecimalFormat("#,###.00"); double number = 1234567.89; String formattedNumber = decimalFormat.format(number); System.out.println(formattedNumber); // 输出: 1,234,567.89 // 格式化货币 DecimalFormat currencyFormat = new DecimalFormat("¤#,###.00"); String formattedCurrency = currencyFormat.format(number); System.out.println(formattedCurrency); // 输出可能类似于: ¥1,234,567.89,具体取决于默认货币符号 // 格式化百分比 DecimalFormat percentFormat = new DecimalFormat("###.00%"); double percentage = 0.12345; String formattedPercent = percentFormat.format(percentage); System.out.println(formattedPercent); // 输出: 12.35%
标签:methods,NumberFormat,format,pattern,numbers,DecimalFormat From: https://www.cnblogs.com/anpeiyong/p/18099816