java中四舍五入后并保留两位小数的方法(以double为例)
1.0 String.format打印
数字格式化说明的格式:
%[argument number][flags][width][.precision]type
argument number:若参数大于1,指定哪一个;
flags:符号,如(+、-、;、.);
width:最小字符数;
.precision:精确度;
type:类型,如f:浮点。
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
//直接输出结果
System.out.println(String.format("%.2f", d));
//输出结果:3.14
}
}
String.format 返回的是String, 若是要数据转换为Double
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
DecimalFormat df = new DecimalFormat("#.##");
Double get_double = Double.parseDouble(String.format("%.2f", d));
System.out.println(get_double);
}
}
2.0 DecimalFormat转换
DecimalFormat是NumberFormat的一个具体子类,用于格式化十进制数字。符号含义:
0(代表一个数字,如果不存在显示0)
符号#(代表一个或多个数字,如果不存在则显示为空)
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(d));
}
}
df.format(d) 返回的是String, 若是要数据转换为Double
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
DecimalFormat df = new DecimalFormat("#.##");
Double get_double = Double.parseDouble(df.format(d));
System.out.println(get_double);
}
}
3.0 BigDecimal.setScale()
此方法用于格式化小数点。
BigDecimal.ROUND_HALF_UP表示四舍五入,setScale(2)表示保留两位小数。
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
BigDecimal bd = new BigDecimal(d);
BigDecimal bd2 = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(bd2);
}
}
数据转换
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
BigDecimal bd = new BigDecimal(d);
BigDecimal bd2 = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
Double get_double=Double.parseDouble(bd2.toString());
System.out.println(get_double);
}
}
4.0 用Math.round()
将数乘以100后四舍五入,再除以100.0
注:java中Math.round()是四舍五入取整,并不能设置保留几位小数。
public class Test {
public static void main(String[] args) {
double d = 3.1415926;
Double get_double = (double) ((Math.round(d * 100)) / 100.0);
System.out.println(get_double);
}
}
作者:AmorFatiYJ
链接:https://www.jianshu.com/p/04b998c2b2eb
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。