如何把一个 float 类型的数据转换为 int 类型? 请教大家,如何把一个 float 类型的数据转换为 int 类型? 比如 float 类型 200f 转化为 int 类型的 200 该如何转化? 如果是带小数点的呢? (比如 1.2200f ),是否要先四舍五入后在转化为 int 类呢?还有不同类型的数据互相转化有什么技巧? 请大家发表一下高见呀. 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 float i=200f;int j=(int)i; 嗯,同意楼上的,还是好好看书吧.不过既来进来了,最简单的就是强制转换了,int i = (int)f;你要四舍五入的话就 int i = Math.round(f+0.5);假如你还要指定在小数点后的第几位四舍五入的话,那就用BigDecimal吧 int i = Math.round(f+0.5);-----------------------------------用round方法问什么还要加0.5?直接用不就是四舍五入了么? 对不起,错了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-3Press any key to continue... http://www.lanlin.net/wangyejiaocheng/ShowArticle.asp?ArticleID=5022比较基本的数据转换 float f = 2.5;int i;i= ( int )f;是旧式的强制类型转换。也可以这样:i = static_cast< int > f; 至于为什么要Math.round(f+0.5)因为round(float a) Returns the closest int to the argumentround() 只转到再近的整数,比如round(5.3)=5 round(5.8)=6而前者是不是符要求的,所以就加0.5符合四舍五入 强制转换不就得啦,直接加个(int) 用包装类吧Float.floatToIntBits(float value) 菜鸟关于类的问题 JAVA线程同步,关于使用synchronized的问题 图片像素问题 有没有人能够告诉我 KJScopeAndSpectrumAnalyser 这个类的具体用法 初学者求简单连接access数据库的例子 这段代码为什么不能编译?谢谢! 帮帮我! 问一个javaScript问题 关于Unicode码转换到GBK码的问题 帮忙侃侃代码:(:等你) 菜鸟 用java 做倒计时器
int j=(int)i;
不过既来进来了,
最简单的就是强制转换了,int i = (int)f;
你要四舍五入的话就 int i = Math.round(f+0.5);
假如你还要指定在小数点后的第几位四舍五入的话,那就用BigDecimal吧
用round方法问什么还要加0.5?
直接用不就是四舍五入了么?
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...
比较基本的数据转换
int i;
i= ( int )f;是旧式的强制类型转换。也可以这样:i = static_cast< int > f;
因为
round(float a)
Returns the closest int to the argument
round() 只转到再近的整数,比如round(5.3)=5 round(5.8)=6
而前者是不是符要求的,所以就加0.5符合四舍五入
Float.floatToIntBits(float value)