double与float运算上的坑

一、Double乘法坑

public static void main(String[] args) {
        String a = "71.57";
        Double v = Double.parseDouble(a) * 100;
        System.out.println(v.longValue());

        BigDecimal bigDecimal = new BigDecimal(a);
        BigDecimal multiply = bigDecimal.multiply(new BigDecimal(100));
        System.out.println(multiply.longValue());
    }

运行结果 :惊不惊喜?!意不意外?!

7156
7157

二、除法喜欢加f的群众

public static void main(String[] args) {
        System.out.println("尾数0加了f:" + String.format("%.2f", 22545600L / 100.0f));
        System.out.println("尾数1加了f:" + String.format("%.2f", 22545601L / 100.0f));
        System.out.println("尾数2加了f:" + String.format("%.2f", 22545602L / 100.0f));
        System.out.println("尾数3加了f:" + String.format("%.2f", 22545603L / 100.0f));
        System.out.println("尾数4加了f:" + String.format("%.2f", 22545604L / 100.0f));
        System.out.println("尾数5加了f:" + String.format("%.2f", 22545605L / 100.0f));
        System.out.println("尾数6加了f:" + String.format("%.2f", 22545606L / 100.0f));
        System.out.println("尾数7加了f:" + String.format("%.2f", 22545607L / 100.0f));
        System.out.println("尾数8加了f:" + String.format("%.2f", 22545608L / 100.0f));
        System.out.println("尾数9加了f:" + String.format("%.2f", 22545609L / 100.0f));
        System.out.println();
        System.out.println("尾数0没加f:" + String.format("%.2f", 22545600L / 100.0));
        System.out.println("尾数1没加f:" + String.format("%.2f", 22545601L / 100.0));
        System.out.println("尾数2没加f:" + String.format("%.2f", 22545602L / 100.0));
        System.out.println("尾数3没加f:" + String.format("%.2f", 22545603L / 100.0));
        System.out.println("尾数4没加f:" + String.format("%.2f", 22545604L / 100.0));
        System.out.println("尾数5没加f:" + String.format("%.2f", 22545605L / 100.0));
        System.out.println("尾数6没加f:" + String.format("%.2f", 22545606L / 100.0));
        System.out.println("尾数7没加f:" + String.format("%.2f", 22545607L / 100.0));
        System.out.println("尾数8没加f:" + String.format("%.2f", 22545608L / 100.0));
        System.out.println("尾数9没加f:" + String.format("%.2f", 22545609L / 100.0));
    }

运行结果:开不开心?

尾数0加了f:225456.00
尾数1加了f:225456.00
尾数2加了f:225456.02
尾数3加了f:225456.05
尾数4加了f:225456.05
尾数5加了f:225456.05
尾数6加了f:225456.06
尾数7加了f:225456.08
尾数8加了f:225456.08
尾数9加了f:225456.08

尾数0没加f:225456.00
尾数1没加f:225456.01
尾数2没加f:225456.02
尾数3没加f:225456.03
尾数4没加f:225456.04
尾数5没加f:225456.05
尾数6没加f:225456.06
尾数7没加f:225456.07
尾数8没加f:225456.08
尾数9没加f:225456.09

你可能感兴趣的:(Java基础)