小数点数字和百分号(百分比)需要进行两者之间相互转换。如代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| String s1 = "21.8%"; String s2 = "-21.7%"; NumberFormat numberFormat = NumberFormat.getPercentInstance(); try { Number n1 = numberFormat.parse(s1); Number n2 = numberFormat.parse(s2); Log.d("小数点字符串转百分数", n1.floatValue() + " , " + n2.floatValue()); } catch (Exception e) { e.printStackTrace(); } float f1 = 0.218f; float f2 = -0.217f; try { numberFormat.setMaximumFractionDigits(3); String s3 = numberFormat.format(f1); String s4 = numberFormat.format(f2); Log.d("小数点数字转百分数字符串", s3 + " , " + s4); } catch (Exception e) { e.printStackTrace(); }
|
BigDecimal 保留两位小数 四舍五入:
1
| new BigDecimal().setScale(2, BigDecimal.ROUND_HALF_UP).toString();
|