优秀的编程知识分享平台

网站首页 > 技术文章 正文

Java double转int的方法(java double 转 integer)

nanyue 2024-09-29 14:56:59 技术文章 4 ℃

强制转换

double保留小数点后一位

Decima2.double转int

int num = (new Double(0.999997)).intValue();

int num = (int)0.999997;

使用DecimalFormat

lFormat df = new DecimalFormat("#.0");

df.format(0.999997);

同理,保留小数点后两位

DecimalFormat df = new DecimalFormat("#.00");

df.format(0.999997);

同理保留小数点后零位

DecimalFormat df = new DecimalFormat("#");

df.format(0.999997);


示例

public class GetInt {

/**

* (1)四舍五入把double转化int整型,0.5进一,小于0.5不进一

* @param number

* @return

*/

public static int getInt(double number){

BigDecimal bd=new BigDecimal(number).setScale(0, BigDecimal.ROUND_HALF_UP);

return Integer.parseInt(bd.toString());

}


/**

* (2)四舍五入把double转化为int类型整数,0.5也舍去,0.51进一

* @param dou

* @return

*/

public static int DoubleFormatInt(Double dou){

DecimalFormat df = new DecimalFormat("######0"); //四色五入转换成整数

return Integer.parseInt(df.format(dou));

}

最近发表
标签列表