下面给你介绍3种常见的四舍五入:
// 方式一:BigDecimal方式
double f = 3.1315
BigDecimal b = new BigDecimal(new Double(f).toString)
double f1 = b.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue()
注意:这里一定不要直接使用new BigDecimal(double)的构造方法,而要使用new BigDecimal(new Double(1.1315).toString())的方式,不然会出现精确问题
// 方式二:DecimalFormat方式
//DecimalFormat默认采用了RoundingMode.HALF_EVEN这种类型,而且format之后的结果是一个字符串类型String
DecimalFormat df = new DecimalFormat("#.000")
System.out.println(df.format(new BigDecimal(1.0145)))//1.014
System.out.println(df.format(new BigDecimal(1.1315)))//1.132
// 方式三:
double d = 3.1415926
String result = String.format("%.2f", d)
// %.2f %. 表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型。
按照你的要求为不确定保留几位小数的字符串做四舍五入的Java程序如下
import java.math.BigDecimal
public class A {
public static void main(String[] args) {
String s="0.00000999999997"
//四舍五入,length是小数位数
int length=s.substring(s.indexOf(".")+1).length()
String s1=String.format("%."+(length-1)+"f",new BigDecimal(s))
//去尾部0
BigDecimal bd=new BigDecimal(s1).stripTrailingZeros()
System.out.println(bd.toPlainString())
}
}