本文實例講述了Android實現(xiàn)的數(shù)字格式化用法。分享給大家供大家參考,具體如下:
package formatnumber;import java.text.DecimalFormat;public class FormatNumber {public static void main(String[] args) {DecimalFormat df = new DecimalFormat();double data = 1234.56789;System.out.println("格式化之前的數(shù)字: " + data);String style = "0.0";//定義要顯示的數(shù)字的格式df.applyPattern(style);// 將格式應(yīng)用于格式化器System.out.println("采用style: " + style + "格式化之后: " + df.format(data));style = "00000.000 kg";//在格式后添加諸如單位等字符 df.applyPattern(style);System.out.println("采用style: " + style + "格式化之后: " + df.format(data));// 模式中的"#"表示如果該位存在字符,則顯示字符,如果不存在,則不顯示。style = "##000.000 kg";df.applyPattern(style);System.out.println("采用style: " + style + "格式化之后: " + df.format(data));// 模式中的"-"表示輸出為負數(shù),要放在最前面style = "-000.000";df.applyPattern(style);System.out.println("采用style: " + style + "格式化之后: " + df.format(data));// 模式中的","在數(shù)字中添加逗號,方便讀數(shù)字style = "-0,000.0#";df.applyPattern(style);System.out.println("采用style: " + style + "格式化之后: " + df.format(data));// 模式中的"E"表示輸出為指數(shù),"E"之前的字符串是底數(shù)的格式,// "E"之后的是字符串是指數(shù)的格式style = "0.00E000";df.applyPattern(style);System.out.println("采用style: " + style + "格式化之后: " + df.format(data));// 模式中的"%"表示乘以100并顯示為百分數(shù),要放在最后。style = "0.00%";df.applyPattern(style);System.out.println("采用style: " + style + "格式化之后: " + df.format(data));// 模式中的"/u2030"表示乘以1000并顯示為千分數(shù),要放在最后。 style = "0.00/u2030";//在構(gòu)造函數(shù)中設(shè)置數(shù)字格式DecimalFormat df1 = new DecimalFormat(style); //df.applyPattern(style);System.out.println("采用style: " + style + "格式化之后: " + df1.format(data));}}程序運行結(jié)果為:
格式化之前的數(shù)字: 1234.56789采用style: 0.0格式化之后: 1234.6采用style: 00000.000 kg格式化之后: 01234.568 kg采用style: ##000.000 kg格式化之后: 1234.568 kg采用style: -000.000格式化之后: -1234.568采用style: -0,000.0#格式化之后: -1,234.57采用style: 0.00E000格式化之后: 1.23E003采用style: 0.00%格式化之后: 123456.79%采用style: 0.00‰格式化之后: 1234567.89‰
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android開發(fā)入門與進階教程》、《Android調(diào)試技巧與常見問題解決方法匯總》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對大家Android程序設(shè)計有所幫助。
新聞熱點
疑難解答