Double rounding values ​​in Java

Possible duplicate:
Radius of doubling to 2 significant digits after the decimal point

I have a matrix. I found the 10th degree of a matrix using Java. After finding the 10th power, I need to round the double values ​​to 3 decimal places. Please help me round the double values ​​in the matrix to 3 decimal places.

+2


a source to share


5 answers


You cannot round values double

to decimal places, as it double

is a binary format, not decimal, and is internally rounded to binary fractions.

Instead, you should do rounding when formatting the output. This can be done in Java in several ways:



String.format("%.2f", 1.2399) // returns "1.24"
new DecimalFormat("0.00").format(1.2)// returns "1.20"
new DecimalFormat("0.##").format(1.2)// returns "1.2"

      

Read the floating point guide for more details .

+4


a source


Or, if you really want to double the value close to the rounded one, you can do something like:

val = Math.round(val * 1000) / 1000.0;

      



where val is the number you want to round. I used 1000 for 3 decimal places; use 10 ^ n for n decimal places.
Also note that after the "/" I used the double literal "1000.0" (with ".0" after "1000") to ensure that the result is double (since Math.round is rounded to a long value).

+1


a source


You can use the DecimalFormat class. Something like that

double unformated = 0.34556 // your double;
double formated = new DecimalFormat("0.###").format((double)unformated);

      

0


a source


Try using java.math.BigDecimal for round:

BigDecimal initialValue = new BigDecimal(65.432105);
double rounded = initialValue.setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println("rounded = " + rounded ); // outputs 65.432

      

0


a source


try the next hidden piece of code. This only works for | values ​​| <Long.Max_VALUE / 1000

public static double round3(double d) {
  return ((double) (long) ((d < 0 ? d - 0.5 : d + 0.5) * 1000))/1000;
}

      

0


a source







All Articles