double保留两位小数(四舍五入)

本文介绍了几种在Java中处理数字的方法,包括对double类型数值进行精确的四舍五入操作、将数值转换为百分比字符串以及获取指定精度的小数点后的数字。这些方法使用了Math类和BigDecimal类来确保计算的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//val为处理double 数字,precsion为保留小数位数。

public static Double roundDouble(double val, int precision) {  
  Double ret = null;  
        try {  
           double factor = Math.pow(10, precision);  
           ret = Math.floor(val * factor + 0.5) / factor;  
        } catch (Exception e) {  
           e.printStackTrace();  
        }  
       return ret;  
    }

 

 

	//	格式化数据
	//将小数转化为百分数,保留2位小数,四舍五入,例:35.21%
	public static String formatRates(double val ) {   
		Double ret = null; 
		val = val*100 ;
		int precision = 2 ;
        try {   
           double factor = Math.pow(10, precision);   
           ret = new Double(Math.floor(val * factor + 0.5) / factor);   
        } catch (Exception e) {   
           e.printStackTrace();   
        }
        String tmp = String.valueOf(ret);
        if (tmp.substring(tmp.indexOf('.')+1).length()<2){
        	tmp = tmp + "0" ;
        }
       return tmp + "%";   
    } 

 

 写道
public static String getRoundValue(double value,int digit) {
digit = (digit < 0 ? 0 : digit );
String s = String.valueOf(new BigDecimal(value).setScale(digit, BigDecimal.ROUND_HALF_UP)
.doubleValue());
return (digit == 0 ? (s.substring(0,s.indexOf('.'))) : s);
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值