java怎么用变量做四舍五入_java自定义实现数值的四舍五入

java自定义实现数值的四舍五入

问题引入:

java的Math类提供的rint()和round()方法,提供了对数值进行舍入的处理,其方法如下:

(double a)返回最接近参数并等于某一整数的double值。

(double a)返回最接近参数的long。(float a)返回最接近参数的int可这三个方法并不能满足实际应用中的所有需要,因此需要自定义一个类实现四舍五入的功能。            public class RoundTool {

//value 进行四舍五入的数值,dotNum 保留的小数位数

public static String round(double value, int dotNum) {

String strValue = String.valueOf(value);

int pos = strValue.indexOf("."); //小数点的位置

int len = strValue.length(); //数值的总位数

int dotLen = len - pos - 1; //实际小数的位数

String endNum = ""; //最后返回的字符串

if (dotNum < dotLen) { // 需要保留的小数位数少于实际的小数位数,即小数有多

String c = strValue.substring(pos + dotNum + 1, pos + dotNum + 2); // 获得保留小数位的下一位,对其进行四舍五入

int cNum = Integer.parseInt(c); // 转换为整数

double tempValue = Double.parseDouble(strValue); // 保留运算结果的中间变量

if (cNum >= 5) { // cNum>=5,进位处理(保留小数位的最后一位加1),若保留两位,则加上0.01

String tempDot = "";

for (int i = 0; i < dotNum - 1; i++) {

tempDot = tempDot + "0";

}

tempDot = "0." + tempDot + "1"; // 需要进位的小数值

tempValue = tempValue + Double.parseDouble(tempDot);

strValue = String.valueOf(tempValue); // 进位后的值转换为字符串

endNum = strValue.substring(0, strValue.indexOf(".") + dotNum + 1);

} else { // cNum<5,直接截取

endNum = strValue.substring(0, strValue.indexOf(".") + dotNum + 1);

}

} else if (dotNum == dotLen) { // 需要保留的小数位数与实际的小数位数相等

endNum = String.valueOf(value);

} else { // 需要保留的小数位数大于实际的小数位数相等

for (int i = 0; i <= dotNum - dotLen - 1; i++) {

strValue = strValue + "0"; // 补“0”

}

endNum = strValue; // 最终的值

}

return endNum;

}

public static void main(String[] args) {

System.out.println("数值123.121保留两位小数:\t" + RoundTool.round(123.121, 2));

System.out.println("数值123.456789保留3位小数:\t" + RoundTool.round(123.456789, 3));

System.out.println("数值123.1231保留3位小数:\t" + RoundTool.round(123.1231, 3));

System.out.println("数值123.5保留3位小数:\t" + RoundTool.round(123.5, 3));

}

}

be0bcb4ed0265421a4d0de61d927397b.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值