上代码
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Demo {
/*
* 获得的是double类型
* m1
*/
public static void m1(double num){
BigDecimal bg = new BigDecimal(num);
double num1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(num1);
}
/*
* 打印的String类型
* m2
*/
public static void m2(double num){
DecimalFormat df = new DecimalFormat(“#0.00”);
System.out.println(df.format(num));
}
/*
* 打印的String类型
* F3查看源代码
* m3
*/
public static void m3(double num){
System.out.println(String.format(“%.2f”, num));
}
/*
* 打印的String类型
* m4
*/
public static void m4(double num){
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(num));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
double dNum = 0.23456732;
m1(dNum);
m2(dNum);
m3(dNum);
m4(dNum);
}
}
还是推荐一个很不错的java学习网站:java学习