這篇文章主要為大家展示了JDK12中怎么使用CompactNumberFormat,內容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
創新互聯是一家專業提供紅山企業網站建設,專注與做網站、成都網站制作、H5技術、小程序制作等業務。10年已為紅山眾多企業、政府機構等服務。創新互聯專業網站設計公司優惠進行中。
簡介
JDK12引入了新的格式化數字的類叫做CompactNumberFormat。主要方便我們對很長的數字進行簡寫。比如1000可以簡寫為1K或者1 thousand。
本文將會講解CompactNumberFormat的基本構成和使用方法,最后在實際的例子中結束文章的講解。
更多內容請訪問www.flydean.com
CompactNumberFormat詳解
CompactNumberFormat做為格式化數字的一部分是NumberFormat的子類。作用就是將數字進行格式化。要想構建一個CompactNumberFormat,最簡單的辦法就是使用NumberFormat.getCompactNumberInstance方法了。
下面是該方法的定義:
public static NumberFormat getCompactNumberInstance(Locale locale, NumberFormat.Style formatStyle)
方法需要傳入兩個參數:Locale和Style。
Locale
Locale代表著本地語言特性,比如在US locale中,10000可以表示為“10K”,而在China locale中,10000中就變成了“1萬”。
Style
Style有兩種類型,short和long。比如說10000的short表示是“10K”,而它的long表示是“10 thousand”。
JDK已經為我們自定義了很多種內置的Compact實現,我們可以直接使用:
@Test public void testCompactNumberFormat(){ NumberFormat fmtShort = NumberFormat.getCompactNumberInstance( Locale.US, NumberFormat.Style.SHORT); NumberFormat fmtLong = NumberFormat.getCompactNumberInstance( Locale.US, NumberFormat.Style.LONG); log.info(fmtShort.format(312)); log.info(fmtShort.format(3123)); log.info(fmtShort.format(31234)); log.info(fmtLong.format(312)); log.info(fmtLong.format(3123)); log.info(fmtLong.format(31234)); }
輸出結果:
312
3K
31K
312
3 thousand
31 thousand
自定義CompactNumberFormat
除了使用NumberFormat工具類之外,我們還可以自定義CompactNumberFormat。
先看下CompactNumberFormat的定義:
public CompactNumberFormat(String decimalPattern, DecimalFormatSymbols symbols, String[] compactPatterns) public CompactNumberFormat(String decimalPattern, DecimalFormatSymbols symbols, String[] compactPatterns, String pluralRules)
CompactNumberFormat可以接受3個或者4個參數的構造函數。
其中decimalPattern和symbols是用來正常解析數字的,compactPatterns則是用來生成縮寫。pluralRules表示的是復數規則。
@Test public void useCustom(){ String[] compactPatterns = {"", "", "", "0千", "0萬", "00萬", "0百萬", "0千萬", "0億", "00億", "0百億", "0千億", "0兆", "00兆", "000兆"}; DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(Locale.CHINA); CompactNumberFormat format = new CompactNumberFormat( decimalFormat.toPattern(), decimalFormat.getDecimalFormatSymbols(), compactPatterns); log.info(format.format(312340000)); }
上面是一個我們自定義的縮寫規則。
輸出結果:
3億
解析CompactNumber
能生成自然也能夠解析,我們看一個解析的例子:
@Test public void testParse() throws ParseException { NumberFormat fmtLong = NumberFormat.getCompactNumberInstance( Locale.US, NumberFormat.Style.LONG); log.info(String.valueOf(fmtLong.parse("3 thousand"))); }
輸出結果:
3000
以上就是關于JDK12中怎么使用CompactNumberFormat的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。
本文題目:JDK12中怎么使用CompactNumberFormat
本文鏈接:http://m.2m8n56k.cn/article36/pjedpg.html
成都網站建設公司_創新互聯,為您提供網站收錄、虛擬主機、網站設計公司、自適應網站、定制網站、網站改版
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:[email protected]。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯