如何得到小数点后只有两位数的双精度值.
例如,如果a = 190253.80846153846
那么结果值应该是a = 190253.80
尝试:
我试过这个:
public static DecimalFormat twoDForm = new DecimalFormat("#0.00");
在代码中
a = Double.parseDouble(twoDForm.format(((a))));
但我得到的价值像190253.81,而不是我想190253.80
那么我应该为它改变什么?
解决方法
因为Math.round()返回与参数最接近的int.通过添加1/2将结果舍入为整数,取结果的最低值,并将结果转换为int类型.
使用Math.floor()
使用Math.floor()
例
public static double roundMyData(double Rval,int numberOfDigitsAfterDecimal) { double p = (float)Math.pow(10,numberOfDigitsAfterDecimal); Rval = Rval * p; double tmp = Math.floor(Rval); System.out.println("~~~~~~tmp~~~~~"+tmp); return (double)tmp/p; }
完整的源代码
class ZiggyTest2{ public static void main(String[] args) { double num = 190253.80846153846; double round = roundMyData(num,2); System.out.println("Rounded data: " + round); } public static double roundMyData(double Rval,numberOfDigitsAfterDecimal); Rval = Rval * p; double tmp = Math.floor(Rval); System.out.println("~~~~~~tmp~~~~~"+tmp); return (double)tmp/p; } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。