Decimal issue's

Discussion in 'Plugin Development' started by yupie_123, Apr 12, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    yupie_123

    So I try to devide 2 integers, that would result in a double. But the issue is, it keeps rounding it to 0 decimals.
    So for instance if the kills are 50 and the deaths are 20, it says that k/d is 2.0 while that is not the case.

    This is my code:
    Code:java
    1. double kd = plugin.getConfig().getInt(
    2. "kills." + player.getName())
    3. / plugin.getConfig().getInt(
    4. "deaths." + player.getName());
    5. player.sendMessage(ChatColor.GREEN + "Your K/D: "
    6. + ChatColor.RED + kd);
    7.  


    How do I make it so that it rounds the double to 2 decimals? Example: K/D = 2.56

    Thank you!
     
  2. Offline

    Derpiee

    Code:java
    1. Math.round(number * 100.0) / 100.0;
     
  3. Offline

    yupie_123

    That doesn't seem to work, I tried it.
    Also the main issue is, that it doesn't show a double. it shows an integer with one decimal 0
    For example: 1.0

    Anyone know what's wrong?

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 7, 2016
  4. Offline

    hexaan

    yupie_123
    When you divide two integers in java it will return the outcome as int form. Try casting them to a double when you do the calculation.

    Try this
    Code:java
    1.  
    2. int kills = plugin.getConfig().getInt(
    3. "kills." + player.getName());
    4. int deaths = plugin.getConfig().getInt(
    5. "deaths." + player.getName());
    6. double kd = (double) kills / (double) deaths;
    7. player.sendMessage(ChatColor.GREEN + "Your K/D: "
    8. + ChatColor.RED + kd);
    9.  


    Edit: Or if I'm not mistaken you can even use the getDouble() method to ensure the number you are getting is already a double.
     
  5. Offline

    yupie_123

    hexaan
    Perfect! It works, but the only issue now is, how do I make it so that it rounds it to 2 decimals? I tried Derpiee 's method but it gives errors: The left-hand side of an assignment must be a variable.
    Thanks!
     
  6. Offline

    hexaan

    yupie_123

    Derpiee Method should work fine for rounding to 2 decimals.

    Can you post what you are trying?
     
  7. Offline

    yupie_123

    Yes ok, it works, sorry forgot to look!
    Thank you!
     
Thread Status:
Not open for further replies.

Share This Page