0

I have a process which returns a floating point number. Then I use the roundToDecimals method to eliminate some digits.

roundToDecimals(weight,3)

----update june 22 2012 : 1.42 am----

public static double roundToDecimals(double d, int c) {
int temp=(int)((d*Math.pow(10,c)));
return (((double)temp)/Math.pow(10,c));
}

---end of update

It works well but returns more than 3 digits after the decimal point if the last digit is zero ex

0.0020
0.0060
0.333
0.071

Does anyone know how to deal with this kind of problem?

  • What is the problem, exactly? That you don't like the appearance of the 0 after the last non-zero digit? Please include the code you use to print the values. – cheeken Jun 21 '12 at 18:48
  • the problems is solved guys. the value is not printed but but write it in a text will and will be read by svmlight. and svmlight always returns error if found more than 3 digit after koma. the problem was i run my java code and the program concurrently, if i stop my java apps then run svmlight it works. – Herman Plani Ginting Jun 21 '12 at 18:57

2 Answers2

2

Consider your 0.333 case. There is no binary floating point (double, float) representation which is exactly 0.333. There's just "the closest value to 0.333" which is what you'd get if you used

double d = 0.333;

(I'm assuming you're complaining about the result of your roundToDecimals method, which I assume is a float or double. It's hard to tell from your question.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Your method cannot possibly work. You can't round a floating-point value to a specific number of decimal places, because a floating-point value doesn't have decimal places. It has binary places. If you want decimal places you have to convert to a decimal radix, e.g. via DecimalFormat or BigDecimal.

user207421
  • 305,947
  • 44
  • 307
  • 483