JAVA中保留指定位数的数据
有时候会遇到将所得结果保留几位小数的问题。
解决方法1:使用DecimalFormat类
步骤:
1.首先创建DecimalFormat类的对象,并设置保留格式;
2.调用format方法,返回对应的字符串。
代码如下所示:
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("0.00");
String format = df.format(3.1415926);
System.out.println(format);
}
}
输出:
3.14
Process finished with exit code 0
保留格式的设置方法,首先保留格式是一个字符串,其中的参数可以去网上搜索,我一般用到的是"0",".“以及”#"这三个。“0"和”#“代表位,例如"0.00"就代表整数部分长度为1位,小数部分长度为2位。
如果是"000.00”,表示整数部分长度为3位,小数部分长度为2位。如果整数部分大于三位,则全部显示,例如:
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("000.00");
String format = df.format(12345.678);
System.out.println(format);
}
}
输出:
12345.68
Process finished with exit code 0
如果整数部分小于三位,则在前面补0:
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("000.00");
String format = df.format(12.678);
System.out.println(format);
}
}
输出:
012.68
Process finished with exit code 0
而"#"则不会补零,其余和"0"是一样的。例如:
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("###.##");
String format = df.format(12.678);
System.out.println(format);
}
}
输出:
12.68
Process finished with exit code 0
由于format自动四舍五入,如果只想保留2位小数,可以先将数据-0.5即可。
解决方法2:使用printf函数
有时候只需要将结果打印出来,因此可以直接使用printf函数。
格式如下
printf(“%总长度.位数f”,double data);
其中总长度代表至少要打印多少字符,例如:
public class Main {
public static void main(String[] args) {
System.out.printf("%6.3f",1234.5678);
}
}
输出
1234.568
Process finished with exit code 0
因为总共至少需要打印6位,实际有8位,因此打印八位。当总长度大于实际输出的时候,就会在前面添0。例如:
public class Main {
public static void main(String[] args) {
System.out.printf("%10.3f",1234.5678);
}
}
输出:
1234.568
Process finished with exit code 0
最后总结一下:第一种作为重点掌握。因为第二种比较基础,且只能输出,不能得到结果进行下一步处理。并且这只是平时用到的比较基础的数字精度处理,可以掌握,如果用到更复杂的再查找即可。