请教大家,如何把一个 float 类型的数据转换为 int 类型? 比如 float 类型 200f 转化为 int 类型的 200 该如何转化? 如果是带小数点的呢? (比如 1.2200f ),是否要先四舍五入后在转化为 int 类呢?
还有不同类型的数据互相转化有什么技巧? 请大家发表一下高见呀.

解决方案 »

  1.   

    float i=200f;
    int j=(int)i;
      

  2.   

    嗯,同意楼上的,还是好好看书吧.
    不过既来进来了,
    最简单的就是强制转换了,int i = (int)f;
    你要四舍五入的话就  int i = Math.round(f+0.5);
    假如你还要指定在小数点后的第几位四舍五入的话,那就用BigDecimal吧
      

  3.   

    int i = Math.round(f+0.5);-----------------------------------
    用round方法问什么还要加0.5?
    直接用不就是四舍五入了么?
      

  4.   

    对不起,错了
    class a
    {
       public static void main(String[] args)
       {
    double x=1.2;
    double y=1.7;
    double z=-2.1;
    double f=-2.9;
    System.out.println(""+Math.round(x)+Math.round(y)+Math.round(z)+Math.round(f));
      }
    }结果:
    12-2-3
    Press any key to continue...
      

  5.   

    http://www.lanlin.net/wangyejiaocheng/ShowArticle.asp?ArticleID=5022
    比较基本的数据转换
      

  6.   

    float f = 2.5;
    int i;
    i= ( int )f;是旧式的强制类型转换。也可以这样:i = static_cast< int > f;
      

  7.   

    至于为什么要Math.round(f+0.5)
    因为
    round(float a) 
              Returns the closest int to the argument
    round() 只转到再近的整数,比如round(5.3)=5 round(5.8)=6
    而前者是不是符要求的,所以就加0.5符合四舍五入
      

  8.   

    强制转换不就得啦,直接加个(int)
      

  9.   

    用包装类吧
    Float.floatToIntBits(float value)