JAVA Double 类型数据保留2位小数

下面我推荐这种方式:

 

    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位):

 

 

posted on 2022-11-08 07:35  小目标青年  阅读(80)  评论(0编辑  收藏  举报