1.保留 n 位小数(并进行四舍五入)
// 对 d保留 n位小数,并进行四舍五入
double d = "72.288";
String s = String.format("%.2f",d);
System.out.println(s); // "72.29"
// 需要时也将 s可以转为 Double类型
d = Double.parseDouble(s);
2.保留 n 位小数(不进行四舍不入)
方式一:正则表达式
Matcher.find()方法查找,Matcher.group()方法取出
// 对 d保留 2位小数,不四舍五入
double d = "72.288";
Matcher matcher = Pattern.compile("\\d*\\.\\d{2}").matcher(""+d);
matcher.find();
String s = matcher.group();
System.out.println(s); // "72.28"
方式二:类型转换
double -> int -> double
double d = 72.288;
int tmp = (int)(d*100);
d = tmp/100.0;
System.out.println(d); // 72.28