简体   繁体   English

Java四舍五入到两位小数

[英]java rounding to two decimals

I have a number 我有一个电话

double num = 1.234567;

and I'm trying to keep only two decimals 我试图只保留两位小数

num = (int)((num * 100) + 0.5) / 100.0;

but the actual number I got is 1.230000000001. 但我得到的实际数字是1.230000000001。 How can I get rid of the 0000000001 part? 如何摆脱0000000001部分?

Try DecimalFormat : 试试DecimalFormat

DecimalFormat twoDp= new DecimalFormat("#.##");
Double.valueOf(twoDp.format(num));

You can't, unless you switch to a decimal radix. 除非切换到十进制基数,否则不能这样做。 Doubles and floats don't have decimal places, they have binary places, so you can't round or truncate them to specific numbers of decimal places except in the cases where the value representations are congruent, ie the negative powers of 2. 双精度和浮点型没有小数位,它们有二进制数,因此您不能将它们四舍五入或截断为特定的小数位数,除非在值表示形式相同的情况下,即2的负幂。

So you have to either use DecimalFormat if you are presenting the result, or BigDecimal if you want to keep computing with it. 因此,如果要显示结果,则必须使用DecimalFormat如果要继续使用它,则必须使用BigDecimal

Any solution that ends by turning the value back into floating point is incorrect. 以该值重新变为浮点数结尾的任何解决方案都是不正确的。

String result = String.format("%.2f", num);

Try this .. this should solve it 试试这个..这应该解决它

       Double num = //value
   num = //arithmetic


   String temp =num.toString().split("\\.")[0];
       int precision=temp.length();
       BigDecimal b =new BigDecimal(num,new MathContext(precision+2));
   System.out.println(b.doubleValue());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM