绘制双精度并显示小数点

本文关键字:小数点 显示 双精度 绘制 | 更新日期: 2023-09-27 18:10:56

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;
        }
    }

然后使用:

将其绘制到屏幕上
        GameRef.SpriteBatch.DrawString(GUIFont, "" + ExperienceTable.PercentToNextLevel, new Vector2((int)player.Camera.Position.X + 1200, (int)player.Camera.Position.Y + 676), Color.White);

为什么小数点不显示?好像数字被四舍五入了

绘制双精度并显示小数点

默认情况下,如果双精度数一开始就是四舍五入,则不显示小数点。我猜player.ExperiencePointsintint除以另一个int总是得到int,结果是一个四舍五入的值。

假设player.ExperiencePoints实际上是int,并且您希望在除它时得到分数,您应该将除法线更改为以下内容:

PercentToNextLevel = (double) player.ExperiencePoints / MaxExperiencePoints;

如果你想显示小数点,即使它是.00,然后将ExperienceTable.PercentToNextLevel更改为如下所示:

ExperienceTable.PercentToNextLevel.ToString("0.00")

.ToString("0.00")将把双精度值转换为带有2位小数的字符串,如果需要,将其四舍五入到2位小数。

我想

PercentToNextLevel = player.ExperiencePoints / MaxExperiencePoints;

是一个整数除法(如果player.ExperiencePoints是整数)。

试试:

PercentToNextLevel = (double)player.ExperiencePoints / MaxExperiencePoints;

如果player.ExperiencePoints也是int,那么将一个整数除以一个整数,结果是一个四舍五入的整数。相反,使用

PercentToNextLevel = (double)player.ExperiencePoints / MaxExperiencePoints