0

i'm looking for a simple code of function on java to round some decimals,

Example : the input number will always be on this format #.## so the code should do this :

input 100.00 result 100.00 rounded by 0.00

input 100.01 result 100.00 rounded by -0.01

input 100.02 result 100.00 rounded by -0.02

input 100.03 result 100.05 rounded by +0.02

input 100.04 result 100.05 rounded by +0.01

i'm not sure if there is a java function that can provide this result.

btkamine
  • 1
  • 1
  • 1

2 Answers2

0

To round to the nearest 0.05, one simple way is to multiply by 20, round to the nearest integer, then divide by 20.

100.00 * 20 = 2000.00    round-> 2000    2000/20 = 100.00
100.02 * 20 = 2000.20    round-> 2000    2000/20 = 100.00
100.04 * 20 = 2000.80    round-> 2001    2001/20 = 100.05
100.06 * 20 = 2001.20    round-> 2001    etc
100.07 * 20 = 2001.40    round-> 2001 
100.08 * 20 = 2001.60    round-> 2002

You have to decide what happens to 100.025, which will dictate whether you use ROUND_HALF_UP, ROUND_HALF_DOWN or ROUND_HALF_EVEN.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
0

I know this is not a Java-Method. But why not use modulus? :)

public static void main(String[] args) {
    for (float number = 0; number<1; number+=0.01f){
        float rounded = round(number);
        System.out.printf("%f -> %.2f\n", number, rounded);
    }
}

public static float round(float number){
    float ret;

    float mod = number % 0.05f;


    if (mod < 0.05f / 2 ){
        ret = number - mod;
    }else{
        ret = number + (0.05f - mod);
    }

    return(ret);
}

Output

0.000000 -> 0.00
0.010000 -> 0.00
0.020000 -> 0.00
0.030000 -> 0.05
0.040000 -> 0.05
0.050000 -> 0.05
0.060000 -> 0.05
0.070000 -> 0.05
0.080000 -> 0.10
0.090000 -> 0.10
0.100000 -> 0.10
0.110000 -> 0.10
0.120000 -> 0.10
0.130000 -> 0.15
0.140000 -> 0.15
0.150000 -> 0.15
0.160000 -> 0.15
0.170000 -> 0.15
0.180000 -> 0.20
0.190000 -> 0.20
0.200000 -> 0.20
0.210000 -> 0.20
0.220000 -> 0.20
0.230000 -> 0.25
0.240000 -> 0.25
0.250000 -> 0.25
0.260000 -> 0.25
0.270000 -> 0.25
...

I did not see any negative values in your question. So I guess this is enough :-)

superm4n
  • 314
  • 2
  • 9