说说 Java 中 float 与 double 转换时的截断与舍入问题

Java 中 float 与 double 在执行向下类型转换时,需要注意数据的截断和舍入问题。

public class TruncateOrRound {

    public static void main(String[] args) {
        double above=0.5,below=0.4;
        float float_above=0.5f, float_below =0.4f;
        
        //截断
        System.out.println("(int)above:"+(int)above);
        System.out.println("(int)below:"+(int)below);
        System.out.println("(int)float_above:"+(int)float_above);
        System.out.println("(int)float_below:"+(int) float_below);

        //四舍五入
        System.out.println("(round)above:"+Math.round(above));
        System.out.println("(round)below:"+Math.round(below));
        System.out.println("(round)float_above:"+Math.round(float_above));
        System.out.println("(round)float_below:"+Math.round(float_below));

    }
}

运行结果:

(int)above:0
(int)below:0
(int)float_above:0
(int)float_below:0
(round)above:1
(round)below:0
(round)float_above:1
(round)float_below:0

  1. float 与 double 类型直接转换为 int 时,小数位会被截断。
  2. 使用 java.lang.Math 的 round() 方法,可以实现四舍五入。
  3. 因为 round() 方法是 java.lang 的一部分,所以可以直接使用。
发布了626 篇原创文章 · 获赞 705 · 访问量 91万+

猜你喜欢

转载自blog.csdn.net/deniro_li/article/details/104108037