zoukankan      html  css  js  c++  java
  • java的四种取整方法

    java 中取整操作提供了四种方法:分别是: 

    public static double ceil(double a)//向上取整

     public static double floor(double a)//向下取整
     public static long round(double a)//四舍五入取整
     public static double rint(double a)//最近取整
     
     

     第一种:ceil是天花板的意思,表示向上取整。   测试: 

    System.out.println(Math.ceil(1.01));
    System.out.println(Math.ceil(-1.01));
    System.out.println(Math.ceil(1.5));
    System.out.println(Math.ceil(-1.5));
     
     

    输出结果: 

    2.0
    -1.0
    2.0
    -1.0
     
     

     第二种:floor是地板的意思,表示向下取整。   测试: 

    System.out.println(Math.floor(1.01));

    System.out.println(Math.floor(-1.01));
    System.out.println(Math.floor(1.5));
    System.out.println(Math.floor(-1.5));
     
     

     输出: 

    1.0

    -2.0
    1.0
    -2.0
     
     

     第三种:round执行的就是数学上的四舍五入运行。   查看它源码可知其与floor方法的关系: 

    public static long round(double a) {
    return (long)floor(a + 0.5d);
        }
     
     

    测试: 

    System.out.println(Math.round(-1.5));
    System.out.println(Math.round(1.5));
    结果:
    -1
    2
     
     

    第四种:最有意思的,返回最接近参数的整数,如果有2个数同样接近,则返回偶数的那个。它有两个特殊的情况:

    1)如果参数本身是整数,则返回本身。

    2)如果不是数字或无穷大或正负0,则结果为其本身。 

    Returns the double value that is closest in value to the argument and is equal to a mathematical integer. If two double values that are mathematical integers are equally close, the result is the integer value that is even. Special cases:  
    If the argument value is already equal to a mathematical integer, then the result is the same as the argument.  

    If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. 

    Parameters:  a a double value. 

    Returns:  the closest floating-point value to a that is equal to a mathematical integer. 
    测试: 

    System.out.println(Math.rint(-1.5));
    System.out.println(Math.rint(1.5));
    System.out.println(Math.rint(-2.5));
    System.out.println(Math.rint(2.5));
    结果:
    -2.0
    2.0
    -2.0
    2.0
     
     
  • 相关阅读:
    iOS10---新特性以及适配点
    linux下,MySQL默认的数据文档存储目录为/var/lib/mysql。
    Linux安装JDK完整步骤
    ajax获取json数据为undefined--原因解析
    怎样用jQuery拿到select中被选中的option的值
    一个Filter需要配置多个url-pattern
    Jquery+Ajax实现Select动态添加数据
    tomcat启动报错:Address already in use: JVM_Bind
    Gson 是google解析Json的一个开源框架,同类的框架fastJson,JackJson
    Java中文乱码解决方案
  • 原文地址:https://www.cnblogs.com/hanxue53/p/4315439.html
Copyright © 2011-2022 走看看