天天看點

android保留兩位小數的方法

1.使用DecimalFormat

float distanceValue = Math.round((distance/10f))/100f;
DecimalFormat decimalFormat =new DecimalFormat(0.00);//構造方法的字元格式這裡如果小數不足2位,會以0補足.
String distanceString = decimalFormat.format(distanceValue) + km;//form
           

at 傳回的是字元串

2.利用标簽

首先在value>string資源檔案重定義String标簽:

<resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">

    <string name="app_name">TextCustomView</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="xliff_test">your name is <xliff:g id="NAME">%1$50s</xliff:g>, and your age is
    <xliff:g id="AGE">%2$1.2f</xliff:g></string>

</resources>
           

然後再代碼中使用: 

String str = res.getString(R.string.xliff_test, xliff,(float)120);

然後得到的字元串就是保留兩位小資料的(補零). 

1.此種方式,在代碼中就不需要再次對資料進行處理,可以簡化代碼與計算。

2.在使用xliff标簽的%n$mf的方式的時候,m可以設定為1.n(n為要保留的小數位數,沒有則補零,前面的1會完整保留目前資料,比如100.2會顯示100.20,不用擔心前面整數部分顯示不正确)。

3.BigDecimal 方法

double f = 111231.5585;
BigDecimal bg = new BigDecimal(f);
double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f1);
           

結果為:111231.56

4.String.format方法

System.out.println(String.format("%.2f", f));
           

結果為:111231.56

5.NumberFormat 方法

NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(f));
           

結果為:111231.56

繼續閱讀