Summing floats doesn't work as expected

edited January 2018 in Questions about Code

I created this simple program:

float threshold = 0.5;

void setup() {
}

void draw() {
}

void keyPressed() {
  if(key == '+') {
    threshold += 0.1;
  }

  if(key == '-') {
    threshold -= 0.1;
  }

  println(threshold);
}

If I press "+" once i read 0.6 in the console, which is what I expected, but if i pressed it again I got: 0.70000005

Same thing happens if I press the "-" key: 0.4 0.3 0.20000002

I'm not sure if it's a bug or something I'm missing with the float primitive.

Tagged:

Answers

  • edited January 2018 Answer ✓

    No, that's right. Floating point numbers are not exact. This is due to how they are stored in memory. See, there are only so many ones and zeros assigned to each number stored in memory, so there has to be some give and take when it comes to storing floats. Basically, the tradeoff is that you can store decimals at the cost of precision.

    https://processing.org/reference/float.html

  • Thanks, that's very clear but now I have another question: is there a way to limit the decimals numbers without converting the variables from float to string and to float again (so without using nf(), nfc(), etc.)?

  • edited January 2018 Answer ✓

    Sure.

    float x = 0.20000002;
    float y = round(10*x)/10.0; // You might also consider using floor().
    println(x);
    println(y);
    
Sign In or Register to comment.