Rounding to 6 decimal places using Math.round method in Java android

◇◆丶佛笑我妖孽 提交于 2019-12-23 05:29:32

问题


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.

Is there any way to use Math.round and have 6 decimal places?


回答1:


You are casting things to Integers which will ruin any rounding. To use doubles, use a decimal point (i.e 100.0 instead of 100). And if you want it with 6 decimals, use 1000000.0 like this:

 double i2 = value * 2.23694; 
 i2 = Math.round(i2*1000000.0)/1000000.0;

But generally I think DecimalFormat is a more elegant solution (guessing you want it rounded only to present it):

DecimalFormat f = new DecimalFormat("##.000000");
String formattedValue = f.format(i2);



回答2:


If you are using the values for displaying just use below method for rounding to 6 digits

double a = 12.345694895;
String str = String.format("%.6f", a );



回答3:


double value = 12.3464367843; double rounded = (double) Math.round(value * 1000000) / 1000000;

output:12.346437



来源:https://stackoverflow.com/questions/22833515/rounding-to-6-decimal-places-using-math-round-method-in-java-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!