Reversed Round Function

Hello fellow programmers!

I was working on a small code snippet and I ran into an issue.

In my project, I use floor() to convert from global coordinates to “chunk” coordinates via a simple mathematic equation: floor(globalCoordinates / chunkSize) which gives me a ratio of the two values which I can then use as a coordinate system for the chunks.

The only issue is that certain values will be misrepresented and will give me the chunk right behind them as opposed the chunk ahead. Use ceil() does not remedy it, as it only applies it to the opposite values.

I attempted to use float() instead but I end up with the worst of both of them. I realize now that if there were some way to switch float from rounding up when it needs to round down (and vise-versa) I wouldn’t have said issue.

If you guys have any ideas as to what I could do to try and make an inverted round() function it would be great!

Hi @Mattyjak,

see below

Cheers
— mnse

void setup() {
  size(500, 500);
  float v1 = 4.49;
  float v2 = 4.5;
  // floor always rounds down
  println("floor("+v1+") = " + floor(v1));
  println("floor("+v2+") = " + floor(v2));
  // ceil always rounds up
  println("ceil("+v1+") = " + ceil(v1));
  println("ceil("+v2+") = " + ceil(v2));
  // round mathematical round < .5 down >= .5 up
  println("round("+v1+") = " + round(v1));
  println("round("+v2+") = " + round(v2));

  // to see how round works see below
  println("myround("+v1+") = " + myround(v1));
  println("myround("+v2+") = " + myround(v2));
}

// round function
// rounds float values < 0.5 down and >= 0.5 up
// so 4.49 becomes 4 and 4.50 becomes 5
int myround(float f) {
  return int(f+0.5);
}

output:

floor(4.49) = 4
floor(4.5) = 4
ceil(4.49) = 5
ceil(4.5) = 5
round(4.49) = 4
round(4.5) = 5
myround(4.49) = 4
myround(4.5) = 5

2 Likes

Hi there! I already know how to use the round, ceil, and floor methods.

What I needed was an inverse to the round function, as in anything below .5 would be rounded up and anything above .5 would be round down.

I came up with my own solution that seems to work fine:

int invRound(float val){
  if(val+0.5 > 1){
    return round(val+0.5)-1;
  }
  return round(val+0.5);
}

It’s pretty simple but it gets the job done.

Thank you anyways for trying <3

Your solution using the ternary operator:

static final int invRound(float val) {
  return (val += .5) > 1? round(val) - 1 : round(val);
}
2 Likes