下面我推荐这种方式:
public static void main(String[] args) { double test1=10.2234; double test2=10.3356; double test3=10.0000; String testStr1 = String.format("%.2f", test1); String testStr2 = String.format("%.2f", test2); String testStr3 = String.format("%.2f", test3); System.out.println("String类型:"); System.out.println(testStr1); System.out.println(testStr2); System.out.println(testStr3); Double dtest1 = Double.valueOf(String.format("%.2f", test1 )); Double dtest2 = Double.valueOf(String.format("%.2f", test2 )); Double dtest3 = Double.valueOf(String.format("%.2f", test3 )); System.out.println("Double类型:"); System.out.println(dtest1 ); System.out.println(dtest2 ); System.out.println(dtest3 ); }
结果(四舍五入保留2位):