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.
a source to share
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 .
a source to share
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).
a source to share
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
a source to share