We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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.
Answers
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.)?
Sure.
Thanks!