1.返回字符串类型,保留后两位:
public static String getRate(Object d) { return String.format("%.2f", d); }
2.返回字符串类型,保留后两位:
public static String getRate1(Object d) { DecimalFormat df = new DecimalFormat(); df.applyPattern("0.00"); return df.format(d); }
3.返回double类型,保留后两位:
//newScale为小数点位数
public static Double roundValue(Double d, int newScale) { Double retValue = null; if (d != null) { BigDecimal bd = new BigDecimal(d); retValue = bd.setScale(newScale,BigDecimal.ROUND_HALF_UP).doubleValue(); } return retValue; }
本文介绍三种在Java中实现数字格式化的方法,包括字符串类型保留两位小数的两种方式,以及返回double类型并保留指定小数位数的函数。通过使用String.format和DecimalFormat类,以及BigDecimal进行精确的数学运算,这些方法能够满足不同场景下的需求。
698

被折叠的 条评论
为什么被折叠?



