Java SE中如何设置或保留特定小数位数?
- 内容介绍
- 文章标签
- 相关推荐
本文共计217个文字,预计阅读时间需要1分钟。
在Java中保留小数的常见方式如下:
javapublic 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(#.##); System.out.println(df.format(a)); System.out.println(df.format(b)); System.out.println(df.format(c)); }}
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);
}
}
本文共计217个文字,预计阅读时间需要1分钟。
在Java中保留小数的常见方式如下:
javapublic 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(#.##); System.out.println(df.format(a)); System.out.println(df.format(b)); System.out.println(df.format(c)); }}
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);
}
}

