String of float .2 comes up as .199

edited November 2013 in Questions about Code

Hello fellow programmers, I am currently working on an idle type game, and I have a "miner" you can hire to mine minerals for you over time. The miners add +.2 to your mineral count every second, and for some reason when it displays the minerals on the screen as a string, it adds .199 minerals at a time instead of .2. The println of the float appears as .2, but for some strange reason it shows up as 1.99 on the string. Anyone know why this could be happening?

class Miner {

  float yield;
  float timer;

  Miner() {
    yield = .2;
    timer = 1*seconds;
    miners++;
     minerImage = loadImage("miner_none.png");
  }

  void draw() {
    update();
    display();
  } 

  void update() {

    if (timer <=0) {
      minerals += yield;
      timer = 1*seconds;
    }

    switch(myPickAxeUpgrade.type) {



    case 2:
      yield=3;
      minerImage = loadImage("miner.png");
      break;


    case 3:
      yield=10;
      minerImage = loadImage("miner_stone.png");
      break;


    case 4:
      yield=30;
      minerImage = loadImage("miner_gem.png");
      break;


    case 5:
      yield=100;
      minerImage = loadImage("miner_godstone.png");
      break;
    }

    timer--;
  }

  void display() {
  }
}

Answers

  • Answer ✓

    Better read reference to float data-type yourself: 8-X
    http://processing.org/reference/float.html

  • edited November 2013 Answer ✓

    Basically the problem is that floats can only represent numbers in a finite way and 1.99 is the closest it can get. Unlike numbers that people generally think in which is base 10, floats are base 2. In base 10 you cannot represent 1.0/3.0 accurately and similarly there are limitations in floats.

    Edit: In addition, there is a limit on the number of digits after a decimal place

  • also, don't loadImage() inside your draw loop. it's massively slow.

    assign global variables, and load them in setup()

Sign In or Register to comment.