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 返回的是字符串
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