0
点赞
收藏
分享

微信扫一扫

【Java SE】保留小数位数


java中保留小数的常见方式

public class Test {
public static void main(String[] args) {
double a = 3.14159265357;
double b = 3.14159265357;
double c = 3.14159265357;

// todo: 方法一
// DecimalFormat 格式化类,将返回格式化后的字符串
// 四舍五入
DecimalFormat df = new DecimalFormat("#.###");
a = Double.parseDouble(df.format(a));
System.out.println(a); // 3.142

// todo: 方法二
// BigDecimal
BigDecimal bd = new BigDecimal(b);
BigDecimal m = bd.setScale(3,BigDecimal.ROUND_HALF_UP);
System.out.println(m); // 3.142

// todo: 方法三
// Math.round
long l = Math.round(c);
System.out.println(l/100.0);
}
}


举报

相关推荐

0 条评论