0
public static double round(double number,int numberofdecimals){
    int n=1;
    for (int i = 1; i <= numberofdecimals;i++){
        n=n*10;
    }


    double  c =((number - Math.floor(number))*n);
    c= Math.floor(c);

    return (Math.floor(number) + (c/n));
}

My method is rounding some doubles perfectly but when I put ((5.0 / 3) ,2) in my number parameter it is giving me 1.6600000 what is going on?

njzk2
  • 38,969
  • 7
  • 69
  • 107
  • 1
    This is simply because the floating point math is broken. See this - http://stackoverflow.com/questions/588004/is-floating-point-math-broken – dryairship May 16 '16 at 13:41
  • I editet the method broj was the number but in my languge i forgot to translate it to english , it is not the problem tho –  May 16 '16 at 13:58
  • It looks like the problem is just due to precision being lost during the calculations. See [this post](http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) for more information. – resueman May 16 '16 at 14:09
  • Milos, please have a look at the question posted by @Blue and see if it has enough information to help you resolve your issue. (hint: it should). – CPerkins May 16 '16 at 15:11
  • not sure what other result you could be expecting, given that you explicitely use `floor` – njzk2 May 16 '16 at 15:47
  • what result do you expect? – Joni May 16 '16 at 16:03

1 Answers1

1

Assuming that you want to do standard rounding (1.5 rounds to 2.0; 1.49 rounds to 1.0) then try the following:

public static double round(double number,int numberofdecimals){
    int n=1;
    for (int i = 1; i <= numberofdecimals;i++){
        n=n*10;
    }

    double  c =((number - Math.floor(number))*n); // Here c = 66.6666666...
    c= Math.floor(c + 0.5); // Now c is 67.0.

    return (Math.floor(number) + (c/n)); // returns 1.67
}
Cheticamp
  • 61,413
  • 10
  • 78
  • 131