在 Java android 中使用 Math.round 方法四舍五入到小数点后 6 位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22833515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rounding to 6 decimal places using Math.round method in Java android
提问by user3456904
I'm using
我正在使用
double i2 = value * 2.23694;
i2 = (double)(Math.round(i2 * 100)) / 100;
for rounding doubles. But it rounds to only 2 decimal places.
为四舍五入双打。但它只四舍五入到小数点后两位。
I want it to be 6 decimal places.
我希望它是 6 位小数。
Is there any way to use Math.round
and have 6 decimal places?
有没有办法使用Math.round
并保留6位小数?
采纳答案by ddmps
You are casting things to Integer
s which will ruin any rounding. To use double
s, use a decimal point (i.e 100.0
instead of 100
). And if you want it with 6 decimals, use 1000000.0
like this:
您正在将内容转换为Integer
s,这将破坏任何舍入。要使用double
s,请使用小数点(即100.0
代替100
)。如果你想用 6 位小数,1000000.0
像这样使用:
double i2 = value * 2.23694;
i2 = Math.round(i2*1000000.0)/1000000.0;
But generally I think DecimalFormatis a more elegant solution (guessing you want it rounded only to present it):
但总的来说,我认为DecimalFormat是一个更优雅的解决方案(猜你想要它四舍五入只是为了呈现它):
DecimalFormat f = new DecimalFormat("##.000000");
String formattedValue = f.format(i2);
回答by Riskhan
If you are using the values for displaying just use below method for rounding to 6 digits
如果您使用的值显示只是使用下面的方法四舍五入到 6 位
double a = 12.345694895;
String str = String.format("%.6f", a );
回答by Sarojini2064130
double value = 12.3464367843; double rounded = (double) Math.round(value * 1000000) / 1000000;
双精度值 = 12.3464367843;double rounded = (double) Math.round(value * 1000000) / 1000000;
output:12.346437
输出:12.346437