java的几种保留小数位数的方法
法一:DecimalFormat
public class DecimalFormatDemo {
public static void main(String[] args) {
double decimal=2.15545422;
DecimalFormat df=new DecimalFormat("#.0000");
String format = df.format(decimal);
double v = Double.parseDouble(format);
System.out.println(v);
}
}
法二:String.format
public class DecimalFormatDemo {
public static void main(String[] args) {
double decimal=2.15555422;
String format = String.format("%.3f", decimal);
double v = Double.parseDouble(format);
System.out.println(v);
}
}
法三:NumberFormat
public class DecimalFormatDemo {
public static void main(String[] args) {
double decimal=2.15555422;
/*DecimalFormat df=new DecimalFormat("#.0000");
String format = df.format(decimal);
double v = Double.parseDouble(format);
System.out.println(v);*/
/*String format = String.format("%.3f", decimal);
double v = Double.parseDouble(format);
System.out.println(v);*/
NumberFormat nf=NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(3);
String format = nf.format(decimal);
double v = Double.parseDouble(format);
System.out.println(v);
}
}
法四:BigDecimal
- ROUND_UP
只要保留位数之后有一位为0就进位,且与正负无关
public class DecimalFormatDemo {
public static void main(String[] args) {
BigDecimal a = new BigDecimal(3.6666666666);
BigDecimal b = new BigDecimal(-3.650000001);
System.out.println(a.setScale(2,BigDecimal.ROUND_UP));
System.out.println(b.setScale(2,BigDecimal.ROUND_UP));
}
}
3.660000001——>3.67
3.666666666——>3.67
-3.65000001——>-3.66
-3.65000000——>3.65
- ROUND_DOWN
向下保留,不管保留位数后面是多少,统统舍去
public class DecimalFormatDemo {
public static void main(String[] args) {
BigDecimal a = new BigDecimal(3.66666666);
BigDecimal b = new BigDecimal(-3.66666666);
System.out.println(a.setScale(2,BigDecimal.ROUND_DOWN));
System.out.println(b.setScale(2,BigDecimal.ROUND_DOWN));
}
}
3.66
-3.66
- ROUND_CEILING 向正无穷方向舍入
public class DecimalFormatDemo {
public static void main(String[] args) {
BigDecimal a = new BigDecimal(3.66666666);
BigDecimal b = new BigDecimal(-3.66666666);
System.out.println(a.setScale(2,BigDecimal.ROUND_CEILING));
System.out.println(b.setScale(2,BigDecimal.ROUND_CEILING));
}
}
3.67
-3.66
- ROUND_FLOOR 向负无穷方向舍入
public class DecimalFormatDemo {
public static void main(String[] args) {
BigDecimal a = new BigDecimal(3.66666666);
BigDecimal b = new BigDecimal(-3.66666666);
System.out.println(a.setScale(2,BigDecimal.ROUND_FLOOR));
System.out.println(b.setScale(2,BigDecimal.ROUND_FLOOR));
}
}
3.66
-3.67
- ROUND_HELF_UP:数字保留法(四舍五入)
public class DecimalFormatDemo {
public static void main(String[] args) {
BigDecimal a = new BigDecimal(3.66666666);
BigDecimal b = new BigDecimal(-3.66666666);
System.out.println(a.setScale(2,BigDecimal.ROUND_HALF_DOWN));
System.out.println(b.setScale(2,BigDecimal.ROUND_HALF_DOWN));
}
}
3.67
-3.67