一、使用BigDecimal的setScale方法
//一、使用BigDecimal的setScale方法
double one11 = 6.866;
BigDecimal two11 = new BigDecimal(one11);
double three11 = two11.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println("一、使用BigDecimal的setScale方法:" + three11);
BigDecimal.ROUND_HALF_UP表示四舍五入,BigDecimal.ROUND_HALF_DOWN也是五舍六入,BigDecimal.ROUND_UP表示进位处理(就是直接加1),BigDecimal.ROUND_DOWN表示直接去掉尾数
二、使用Sting自带的format方法
//二、使用Sting自带的format方法
double one22 = 6.866;
String str22 = String.format("%.2f",one22);
double four22 = Double.parseDouble(str22);
System.out.println("二、使用Sting自带的format方法:" + four22);
三、使用NumberFormat设置最大小数位数
//三、使用NumberFormat设置最大小数位数
double d33 = 6.866;
NumberFormat nf33 = NumberFormat.getNumberInstance();
// 保留两位小数
nf33.setMaximumFractionDigits(2);
// 如果不需要四舍五入,可以使用RoundingMode.DOWN
nf33.setRoundingMode(RoundingMode.UP);
System.out.println("三、使用NumberFormat设置最大小数位数:" + nf33.format(d33));
RoundingMode.HALF_DOWN表示 五舍六入,负数先取绝对值再五舍六入再负数,RoundingMode.HALF_UP:表示四舍五入,负数先取绝对值再五舍六入再负数
四、使用DecimalFormat,#.00为保留两位小数
//四、使用DecimalFormat,#.00为保留两位小数
double f44 = 6.866;
DecimalFormat df44 = new DecimalFormat("#.00");
System.out.println("四、使用DecimalFormat,#.00为保留两位小数:" + df44.format(f44));
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class CutPoint {
public static void main(String[] args) {
//一、使用BigDecimal的setScale方法
double one11 = 6.866;
BigDecimal two11 = new BigDecimal(one11);
double three11 = two11.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println("一、使用BigDecimal的setScale方法:" + three11);
//二、使用Sting自带的format方法
double one22 = 6.866;
String str22 = String.format("%.2f",one22);
double four22 = Double.parseDouble(str22);
System.out.println("二、使用Sting自带的format方法:" + four22);
//三、使用NumberFormat设置最大小数位数
double d33 = 6.866;
NumberFormat nf33 = NumberFormat.getNumberInstance();
// 保留两位小数
nf33.setMaximumFractionDigits(2);
// 如果不需要四舍五入,可以使用RoundingMode.DOWN
nf33.setRoundingMode(RoundingMode.UP);
System.out.println("三、使用NumberFormat设置最大小数位数:" + nf33.format(d33));
//四、使用DecimalFormat,#.00为保留两位小数
double f44 = 6.866;
DecimalFormat df44 = new DecimalFormat("#.00");
System.out.println("四、使用DecimalFormat,#.00为保留两位小数:" + df44.format(f44));
}
}