public static void main(String[] args){
double p = 8.04;
int p_i = (int)(p*100);
System.out.println(p_i);
}
期望结果是804, 实际结果是803。
请用比较有效率的方式实现,谢谢!
public static void main(String[] args){
double p = 8.04;
int p_i = Math.round(p*100);
System.out.println(p_i);
}
这个应该可以达到你想要的
两种方式:
1、通过强制类型转换
1
2
float a=1.1f;//定义一个浮点变量a
int b = (int)a;//这里使用(int)方式对float进行强转,结果为1
2、通过转换为字符串,在截取整数部分
1
2
3
4
5
float a = 1.1f;//定义一个浮点变量a
String str = String.valueOf(a);//浮点变量a转换为字符串str
int idx = str.lastIndexOf(".");//查找小数点的位置
String strNum = str.substring(0,idx);//截取从字符串开始到小数点位置的字符串,就是整数部分
int num = Integer.valueOf(strNum);//把整数部分通过Integer.valueof方法转换为数字
public static void main(String[] args){
double p = 8.04;
String a = (p + "").replace(".", "");
System.out.println(Integer.parseInt(a));
}
用BigDecimal呗
降精度
double p = 8.04d;
float f = (float) p;
int p_i = (int)(f*100);
System.out.println(p_i);
package num;
import java.text.DecimalFormat;
public class num{
public static void main(String[] args){
DecimalFormat df = new DecimalFormat("0"); //四色五入转换成整数 ,这里注意不能有小数点,不然后面转为整形会报错
double p = 8.04;
double p_d = 8.04 *100;
int p_i = Integer.parseInt(df.format(p_d));
System.out.println(p_i );
}
}
double p = 8.04,l=100;
BigDecimal bigDecimal1 = new BigDecimal(Double.toString(p));
System.out.println(bigDecimal1.multiply(new BigDecimal(Double.toString(l))).intValue());//精确的输出
public static void main(String[] args) {
double p = 8.04;
System.out.println((int)Math.ceil((double)(p*100)));
}
正常,java浮点数运算靠不住,最靠不住就是javaScrip了
测试来看 p * 100 结果是803.999999999999999 ,强制转换为803了