double/float转换为int类型
1.强制类型转换
package Test;
/**
* @author Marston
* @date 2021/9/28
*/
public class test1 {
public static void main(String[] args) {
double dou = 18.165985;
float flo = 18.1612f;
//将double/float转换为int —使用类型转换
int douInt = (int)dou;
int floInt = (int) flo;
System.out.println("double:"+dou+",转换为的int:"+douInt);//double:18.165985,转换为的int:18
System.out.println("float:"+flo+",转换为的int:"+floInt);//float:18.1612,转换为的int:18
}
}
2.使用math函数,比如Math.round()
package Test;
/**
* @author Marston
* @date 2021/9/28
*/
public class test1 {
public static void main(String[] args) {
double dou = 18.165985;
float flo = 18.1612f;
//将double/float转换为int —使用类型转换
int douInt = (int) Math.round(dou);//首先通过math函数为long类型,然后再强制转换为int类型
int floInt = Math.round(flo);
System.out.println("double:"+dou+",转换为的int:"+douInt);//double:18.165985,转换为的int:18
System.out.println("float:"+flo+",转换为的int:"+floInt);//float:18.1612,转换为的int:18
}
}
//将double转换为int —使用 Math.round(),四舍五入获取
选择要保留的小数点个数
四舍五入(只能保留一位小数)
package Test;
/**
* @author Marston
* @date 2021/9/28
*/
public class test1 {
public static void main(String[] args) {
double dou = 18.165985;
float flo = 18.1612f;
//四舍五入,先乘100,再除100
double douInt = (double) (Math.round(dou*100)/100);
double floInt = Math.round(flo*100)/100;
System.out.println("double:"+dou+",转换为的double:"+douInt);//double:18.165985,转换为的double:18.0
System.out.println("float:"+flo+",转换为的float:"+floInt);//float:18.1612,转换为的float:18.0
}
}
使用DecimalFormat(转换为字符串)
保留两位
package Test;
import java.text.DecimalFormat;
/**
* @author Marston
* @date 2021/9/28
*/
public class test1 {
public static void main(String[] args) {
double dou = 18.165985;
float flo = 18.1612f;
//四舍五入,先乘100,再除100
DecimalFormat df = new DecimalFormat("#.00");
String f = df.format(dou);
String f1 = df.format(flo);
System.out.println("double:"+dou+",转换为保留多位小数double:"+f);//double:18.165985,转换为保留多位小数double:18.17
System.out.println("float:"+flo+",转换为的float:"+f1);//float:18.1612,转换为的float:18.16
}
}
保留2位+,依此类推
package Test;
import java.text.DecimalFormat;
/**
* @author Marston
* @date 2021/9/28
*/
public class test1 {
public static void main(String[] args) {
double dou = 18.165985;
float flo = 18.1612f;
//四舍五入,先乘100,再除100
DecimalFormat df = new DecimalFormat("#.00000");
String f = df.format(dou);
String f1 = df.format(flo);
System.out.println("double:"+dou+",转换为保留多位小数double:"+f);//double:18.165985,转换为保留多位小数double:18.16598
System.out.println("float:"+flo+",转换为的float:"+f1);//float:18.1612,转换为的float:18.16120
}
}