NumberFormat數字格式化


1.NumberFormat表示數字的格式化類

比較全的學習鏈接:https://www.cnblogs.com/baiqiantao/p/6738842.html

1    public static Locale[] getAvailableLocales()              普通    返回所有語言環境的數組
2    public static final NumberFormat getInstance()            普通    返回當前默認語言環境的數字格式
3    public static NumberFormat getInstance(Locale inLocale)       普通    返回指定語言環境的數字格式
4    public static final NumberFormat getCurrencyInstance()        普通    返回當前缺省語言環境的通用格式,根據當前語言環境獲取貨幣數值格式。
5    public static NumberFormat getCurrencyInstance(Locale inLocale) 普通    返回指定語言環境的數字格式    //Locale.CHINA  ¥3.4
            getPercentInstance()        方法獲取百分比的數值格式  

  是NumberFormat的子類

2.DecimalFormat格式化數字

允許我們指定格式模式獲取我們想要的格式化數值,數值的小數部分,默認顯示3位小數

            Double  d=Double.parseDouble(num);
            java.text.NumberFormat percentFormat =java.text.NumberFormat.getPercentInstance(); 
            percentFormat.setMaximumFractionDigits(2); //最大小數位數
            percentFormat.setMaximumIntegerDigits(3);//最大整數位數
            percentFormat.setMinimumFractionDigits(2); //最小小數位數
            percentFormat.setMinimumIntegerDigits(1);//最小整數位數
            return percentFormat.format(d);//自動轉換成百分比顯示
0    表示一個數字,被格式化數值不夠的位數會補0
#    表示一個數字,被格式化數值不夠的位數會忽略
.    小數點分隔符的占位符
,    分組分隔符的占位符
-    缺省負數前綴
%    將數值乘以100並顯示為百分數
\u2030    將數值乘以1000並顯示為千分數
DecimalFormat format1 = new DecimalFormat("#\u2030");
System.out.println(format1.format(0.3345));//輸出334‰
 
DecimalFormat format2 = new DecimalFormat("##.##");
System.out.println(format2.format(12.345));//輸出12.35
 
DecimalFormat format3 = new DecimalFormat("0000.00");
System.out.println(format3.format(12.345));//輸出0012.35
 
DecimalFormat format4 = new DecimalFormat("#.##%");
System.out.println(format4.format(12.345));//輸出1234.5%

FormatDemo demo=new FormatDemo();
  demo.format("###,###.###", 111222.34567);
  demo.format("000,000.000", 11222.34567);
  demo.format("###,###.###$", 111222.34567);
  demo.format("000,000.000¥", 11222.34567);
  demo.format("##.###%", 0.345678);        // 使用百分數形式
  demo.format("00.###%", 0.0345678);        // 使用百分數形式
  demo.format("###.###\u2030", 0.345678);    // 使用千分數形式
 

3.ChoiceFormat格式化數字

ChoiceFormat允許將格式化運用到某個范圍的數,通常與MessageFormat一同使用。ChoiceFormat在構造方法中接收一個format數組和一個limits數組,這兩個數組的長度必須相等,例如

limits = {1,2,3,4,5,6,7}
formats = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}

limits數組實際上是個區間,可開可閉,並且必須按升序排列,如果不按升序排列,格式化結果將會不正確,還可以使用\u221E(表示無窮大)。

ChoiceFormat的匹配公式

limit[j] <= X <limit[j+1]

其中X表示使用format方法傳入的值,j表示limit數組中的索引。當且僅當上述公式成立時,X匹配j,如果不能匹配,則會根據X是太小還是太大,匹配limits數組的第一個索引或最后一個索引,然后使用匹配的limits數組中的索引,去formats數組中尋找相同索引的值。例子:

double[] limits = { 3, 4, 5, 6, 7, 8, 9 };
String[] formats = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" };
ChoiceFormat format = new ChoiceFormat(limits, formats);
System.out.println(format.format(2.5));//將會輸出"星期一"
/**3.6介於3和4之間,所以會匹配3,又由於3在limits數組中的索引是0,所以會在formats數組徐照索引0的值,即輸出"星期一"
*/
System.out.println(format.format(3.6));

下面看一下ChoiceFormat類中的幾個常用方法

1.nextDouble(double d)靜態方法查找大於d的最小double值,用在limits數組中,從而使limits數組形成一個右開區間數組,例如

limits = {0,1,ChoiceFormat.nextDouble(1)}

2.nextDouble(double d, boolean positive)靜態方法,如果positive參數為true,表示查找大於d的最小double值;如果positive參數為false,表示查找小於d的最大double值,這樣就可以使limits形成一個左開區間數組。

3.previousDouble(double d)靜態方法,查找小於d的最大double值
ChoiceFormat類的構造方法也允許我們傳入一個模式字符串,format方法會根據這個模式字符串執行格式化操作。一個模式元素的格式如下:

doubleNum [占位符] formatStr

占位符可以使用#、< 、\u2264(<=)

ChoiceFormat cf = new ChoiceFormat("1#is 1 | 1<is more than 1");
System.out.println(cf.format(1));//輸出"is 1"
System.out.println(cf.format(2));//輸出"is more than 1"
System.out.println(cf.format(0));//輸出"is 1"

由上面的例子可以看出,模式字符串中的每個模式元素之間使用"|"分割,"|"前后可以添加空格以美化代碼,而且必須按照升序進行書寫,否則會出現java.lang.IllegalArgumentException的運行時異常。
觀看ChoiceFormat類的源碼我們得知,實際上在內部,模式字符串還是被轉換為limits和formats兩個數組。在源碼中

public ChoiceFormat(String newPattern)  {
     applyPattern(newPattern);
}
/** applyPattern(newPattern)方法的部分源碼
*/
public void applyPattern(String newPattern) {
...
choiceLimits = new double[count];
System.arraycopy(newChoiceLimits, 0, choiceLimits, 0, count);
choiceFormats = new String[count];
System.arraycopy(newChoiceFormats, 0, choiceFormats, 0, count);
...
}

可以看出ChoiceFormat(String newPattern)調用了applyPattern(String newPattern)方法,在applyPattern方法中對newPattern字符串進行解析,然后將解析后的數據放置到ChoiceFormat類的兩個私有屬性double[] choiceLimitsString[] choiceFormats中,然后使用格式化方法即可。

3.MessageFormat

MessageFormat提供了以語言環境無關的生成連接消息的方式。
常用MessageFormat的靜態方法format,該方法接收一個字符串的模式和一組對象(對象數組),按照模式形式將格式化的對象插入到模式中,然后返回字符串結果。
MessageFormat的格式模式元素(FormatElement)形式如下:
{ArgumentIndex}
{ArgumentIndex,FormatType}
{ArgumentIndex,FormatType,FormatStyle}
其中ArgumentIndex對象數組中的索引,從0開始,
FormatType包括number、date、 time、choice,
FormatStyle包括short、medium、long、full、integer、currency、percent、SubformatPattern(子模式),
在MessageFormat類的內部,FormatType和FormatStyle實際上是創建格式元素的Format示例
number對應了NumberFormat,其子格式對應了DecimalFormat
date和time對應了DateFormat,其資格是對應了SimpleDateFormat
choice對應了ChoiceFormat
敢說沒有意思,來多舉幾個栗子:
你可以直接使用MessageFormat類中的靜態方法format,像這樣:

/**這是源碼注釋中的一個例子
* 在這個例子中靜態方法format第一個參數是字符串類型的,
* 即模式字符串,第二個參數是個可變參數,實際上就是一個Object類型的數組。
* 在模式字符串中使用"{}"標識一個FormatElement。"{}"中的ArgumentIndex對應Object數組中響應索引處的值。
*/
int planet = 7;
String event = "a disturbance in the Force";
String result = MessageFormat.format("At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
                  planet, new Date(), event);
System.out.println(result);
//輸出:At 20:39:15 on 2015-12-11, there was a disturbance in the Force on planet 7.

你也可以使用MessageFormat的構造方法傳入pattern string(模式字符串),然后調用普通的format方法,在這里就不舉栗子了。
我們不僅被允許使用MessageFormat類中提供默認的FormatElement去format這些對象,還可以設置自己的Format對象format這些Object。

/**在這個例子中,MessageFormat和ChoiceFormat被結合使用
* MessageFormat類中有3個方法值的我們關注
* 1.setFormatByArgumentIndex(int argumentIndex, Format newFormat)//
* 2.setFormats(Format[] newFormats)
* 3.setFormat(int formatElementIndex, Format newFormat)
* 在這個例子當中,在MessageFormat的模式字符串的FormatElement(即{}中的內容)中
* 索引為0的地方將使用ChoiceFormat的格式去格式化。
* 如果在set的Format中仍具有FormatElement,則會遞歸調用MessageFormat的format方法。
*/
MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
double[] filelimits = { 0, 1, 2 };
String[] filepart = { "no files", "one file", "{0,number} files" };
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
form.setFormatByArgumentIndex(0, fileform);
int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = { new Long(fileCount), diskName };
System.out.println(form.format(testArgs));
//輸出:The disk "MyDisk" contains 1,273 files.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM