简体   繁体   中英

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

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?

You are casting things to Integer s which will ruin any rounding. To use double s, use a decimal point (ie 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);

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 );

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

output:12.346437

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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