How do you calculate percentages in Java?

3

So I am trying to make a game with a health bar for the player but whenever I use cross products or any other method of math that should work the percentage result is 0.0... Here is the .java file that handles this:

package com.game.graphics;

import com.game.entity.mob.Mob;

public class HUD {
    Mob target;
    Sprite healthbar;
    Sprite bgBar;

    double percent_normal;

    public HUD(Mob target) {
        this.target = target;
        bgBar = new Sprite(0xff777777, 104, 8);
        healthbar = new Sprite(0xffFF0000, 100, 6);
    }

    public void update() {
        percent_normal = target.getHealth() / 100;
        percent_normal *= target.getMaxHealth();
    }

    public void printData() {
        System.out.println("Normal(" + percent_normal + ")");
    // if the targets's health is any lower than the max health then this seems to always return 0
    }

    public void render(Screen s) {
        s.renderSprite(5, 5, bgBar, false);
        s.renderSprite(7, 6, new Sprite(0xffFF0000, (int) percent_normal, 6), false);
    }
}

I'm not sure if my Math is completely off or if I'm going about this horibly wrong. I've tried looking up how to calculate it to no avail so that's why I'm putting this question here.

java
math
asked on Stack Overflow Aug 17, 2015 by draco miner • edited Aug 17, 2015 by Ian2thedv

3 Answers

8

Shouldn't it be this? :

public void update() {
    percent_normal = target.getHealth() / target.getMaxHealth();
    percent_normal *= 100;
}

E.g. : Player has 120 health and maximum health is 180. This is, 120 / 180 = 0.66666666666 which gives in percentage 0.66666666666 * 100 = 66,66...% instead of 120 / 100 = 1.2 and multiplying this by target.getMaxHealth() which is 180, results in (1.2 * 180) > 100.

answered on Stack Overflow Aug 17, 2015 by Kevin • edited Mar 5, 2016 by Kevin
6

Your way of calculating the percentage seems to be off. To calculate the percentage of X compared to Y you have to do:

double result = X/Y;
result = result * 100;

So in this case your code should look like

public void update() {
    percent_normal = target.getHealth() / target.getMaxHealth();
    percent_normal *= 100;
}

The reason you are always getting 0.0 although is because of the int 100. I believe the target.getHealth()/100 will return a value that is in the form of 0.x and will be turned into int 0 before being cast to double.

answered on Stack Overflow Aug 17, 2015 by ThomasS
0

Basically to calculate percentage we use this,

percentage = (a / b) * 100

So in your case update() method is wrong and replace with code below,

public void update()
{
    percent_normal = target.getHealth() / target.getMaxHealth();
    percent_normal * = 100;
}

Here is an example, just for reference - http://www.flowerbrackets.com/java-calculate-percentage/

answered on Stack Overflow Oct 19, 2017 by Shiva • edited Jul 31, 2019 by Shiva

User contributions licensed under CC BY-SA 3.0