在將float或double轉型為整型值時,總是對該數字執行截尾,如下例:
- public class CastingNumbers{
- public static void main(String[] args){
- double above = 0.7,below = 0.4;
- float fabove = 0.7f, fbelow = 0.4f;
- System.out.println("(int)above: " + (int)above);
- System.out.println("(int)below: " + (int)below);
- System.out.println("(int)fabove: " + (int)fabove);
- System.out.println("(int)fbelow: " + (int)fbelow);
- }
- }
輸出:
(int)above: 0 (int)below: 0 (int)fabove: 0 (int)fbelow: 0
如果想要得到捨入的結果,就需要使用Java.lang.Math中的round()方法:
- public class RoundingNumbers{
- public static void main(String[] args){
- double above = 0.7,below = 0.4;
- float fabove = 0.7f, fbelow = 0.4f;
- System.out.println("Math.round(above): " + Math.round(above));
- System.out.println("Math.round(below): " + Math.round(below));
- System.out.println("Math.round(fabove): " + Math.round(fabove));
- System.out.println("Math.round(fbelow): " + Math.round(fbelow));
- }
- }
輸出:
Math.round(above): 1 Math.round(below): 0 Math.round(fabove): 1 Math.round(fbelow): 0
由於round()是Java.lang的一部分,因此在使用它事不需要額外的導入。