実際に数値を入れていろいろとためしてみた。
特に、負の数はどんなふうに処理されるのかのサンプル。

ソースコード


import java.text.*;
 
public class MathSample {
 
  public static void main(String[] args) {
    
    double[] testcase = {
      -1.1, -1.0, -0.6, -0.5, -0.4, -0.0, 0.0, 0.4, 0.5, 0.6, 1.0, 1.1};
 
    System.out.println("----- (int)cast -----");
    for(int i=0; i<testcase.length; i++){
      System.out.println(
        f(testcase[i]) + " -> " + f((int)testcase[i]));
    }
    
    System.out.println("----- Math.ceil -----");
    for(int i=0; i<testcase.length; i++){
      System.out.println(
        f(testcase[i]) + " -> " + f(Math.ceil(testcase[i])));
    }
    
    System.out.println("----- Math.floor -----");
    for(int i=0; i<testcase.length; i++){
      System.out.println(
        f(testcase[i]) + " -> " + f(Math.floor(testcase[i])));
    }
 
    System.out.println("----- Math.rint -----");
    for(int i=0; i<testcase.length; i++){
      System.out.println(
        f(testcase[i]) + " -> " + f(Math.rint(testcase[i])));
    }
 
    System.out.println("----- Math.round -----");
    for(int i=0; i<testcase.length; i++){
      System.out.println(
        f(testcase[i]) + " -> " + f(Math.round(testcase[i])));
    }
  }
 
  // セミコロンより左が正の数のためのパターン
  // セミコロンより右が負の数のためのパターン
  private static final Format formatter =
    new java.text.DecimalFormat(" 0.0;-0.0");
 
  private static String f(double d){
    return formatter.format(d);
  }
}

出力結果


----- (int)cast -----
-1.1->-1.0
-1.0->-1.0
-0.6-> 0.0
-0.5-> 0.0
-0.4-> 0.0
-0.0-> 0.0
 0.0-> 0.0
 0.4-> 0.0
 0.5-> 0.0
 0.6-> 0.0
 1.0-> 1.0
 1.1-> 1.0
----- Math.ceil -----
-1.1->-1.0
-1.0->-1.0
-0.6->-0.0
-0.5->-0.0
-0.4->-0.0
-0.0->-0.0
 0.0-> 0.0
 0.4-> 1.0
 0.5-> 1.0
 0.6-> 1.0
 1.0-> 1.0
 1.1-> 2.0
----- Math.floor -----
-1.1->-2.0
-1.0->-1.0
-0.6->-1.0
-0.5->-1.0
-0.4->-1.0
-0.0->-0.0
 0.0-> 0.0
 0.4-> 0.0
 0.5-> 0.0
 0.6-> 0.0
 1.0-> 1.0
 1.1-> 1.0
----- Math.rint -----
-1.1->-1.0
-1.0->-1.0
-0.6->-1.0
-0.5->-0.0
-0.4->-0.0
-0.0->-0.0
 0.0-> 0.0
 0.4-> 0.0
 0.5-> 0.0
 0.6-> 1.0
 1.0-> 1.0
 1.1-> 1.0
----- Math.round -----
-1.1->-1.0
-1.0->-1.0
-0.6->-1.0
-0.5-> 0.0
-0.4-> 0.0
-0.0-> 0.0
 0.0-> 0.0
 0.4-> 0.0
 0.5-> 1.0
 0.6-> 1.0
 1.0-> 1.0
 1.1-> 1.0

tags: zlashdot Java Java

Posted by NI-Lab. (@nilab)