Drawing a double and showing the decimal places?
public class ExperienceTable
{
public static int MaxExperiencePoints;
public static double PercentToNextLevel;
public static void checkLevel(Hero player)
{
if (player.ExperiencePoints >= 0)
{
player.Level = 1;
MaxExperiencePoints = 15;
PercentToNextLevel = player.ExperiencePoints / MaxExperiencePoints;
}
}
Then drawing it to the screen using:
GameRef.SpriteBatch.DrawString(GUIFont, "" + ExperienceTable.PercentToNextLevel, new Vector2((int)player.Camera.P开发者_如何学Goosition.X + 1200, (int)player.Camera.Position.Y + 676), Color.White);
How come decimal places don't show up? Seems like the numbers are being rounded.
By default, the decimal place will not be shown if the double is already a rounded number in the first place. I'm guessing player.ExperiencePoints
is an int
. And int
divided by another int
will always result to an int
, resulting in a rounded value.
Assuming that player.ExperiencePoints
is really an int
, and you want to have the fraction when dividing it, you should change the division line to the following:
PercentToNextLevel = (double) player.ExperiencePoints / MaxExperiencePoints;
And if you want to have the decimal places displayed eventhough it's .00
, then change the ExperienceTable.PercentToNextLevel
to something like the following.
ExperienceTable.PercentToNextLevel.ToString("0.00")
.ToString("0.00")
will convert the double value to a string with 2 decimal places, and will round it to two decimal places if it have to.
I think
PercentToNextLevel = player.ExperiencePoints / MaxExperiencePoints;
is an integer division (that's if player.ExperiencePoints
is an integer).
Try that:
PercentToNextLevel = (double)player.ExperiencePoints / MaxExperiencePoints;
If player.ExperiencePoints
is also an int
, then you are dividing an integer by an integer, and the result is a rounded integer. Instead, use
PercentToNextLevel = (double)player.ExperiencePoints / MaxExperiencePoints
精彩评论