开发者

roundoff double values in Java [duplicate]

This question already has answers here: 开发者_C百科 Closed 10 years ago.

Possible Duplicate:

Round a double to 2 significant figures after decimal point

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


You can't really round double values to decimal places since double is a binary format, not decimal, and will internally be rounded to binary fractions.

Instead, you should do the rounding when you format the output. This can be done in Java in a number of 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 detailed information.


Or if you really want a double with the value (close to) rounded you could do something like:

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

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


You can use DecimalFormat class. Something like this

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


Try using java.math.BigDecimal to 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


try the following obsurce 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜