finity和infinity

infinity:無窮的; finity:有限的; 看了下jdk1.8中Double的API,有兩個方法:測試

/**
     * Returns {@code true} if the specified number is infinitely
     * large in magnitude, {@code false} otherwise.
     *
     * @param   v   the value to be tested.
     * @return  {@code true} if the value of the argument is positive
     *          infinity or negative infinity; {@code false} otherwise.
     */
    public static boolean isInfinite(double v) {
        return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY);
    }

    /**
     * Returns {@code true} if the argument is a finite floating-point
     * value; returns {@code false} otherwise (for NaN and infinity
     * arguments).
     *
     * @param d the {@code double} value to be tested
     * @return {@code true} if the argument is a finite
     * floating-point value, {@code false} otherwise.
     * @since 1.8
     */
    public static boolean isFinite(double d) {
        return Math.abs(d) <= DoubleConsts.MAX_VALUE;
    }

而後寫了個測試類,實驗了下code

public class UnitTest {
  @Test
  public void testDouble(){
    double d=0.00/20.00;    
    System.out.println(d+"是否爲有限"+Double.isFinite(d));
    double e=20.00/0.00;
    System.out.println(e+"是否爲無限:"+Double.isInfinite(e));

     DecimalFormat df = new DecimalFormat("0.00");//格式化小數   
    String s = df.format(e);
    System.out.println(s);
    System.out.println(df.format(d));
  }

若是有用到求百分比的,應該判斷下是否爲無限值,這樣會避免一些顯示問題;orm

  • 雖然double是原生類,但JVM實際上是把它當成引入類使用的.全部輸出e爲'infinity'
相關文章
相關標籤/搜索