Java - problems with truncation and rounding

When casting directly, the number is always truncated. If you want to get rounded results, you need to use the round() method in java.lang.Math.

 1 import java.util.*;
 2 
 3 public class CastingNumbers {
 4     public static void main(String[] args) {
 5     double above=0.7,below=0.4;
 6     float fabove=0.7f,fbelow=0.4f;
 7     System.out.println("(int)above:"+(int)above);
 8     System.out.println("(int)below:"+(int)below);
 9     System.out.println("(int)fbelow:"+(int)fbelow);
10     System.out.println("(int)fabove:"+(int)fabove);
11     System.out.println();
12     System.out.println("Math.round(above):"+Math.round(above));
13     System.out.println("Math.round(below):"+Math.round(below));
14     }
15 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325210919&siteId=291194637