如何在 C# 中舍入 float 变量

How to round float variables in C#

我正在用 C# 为游戏创建计时器:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;       // key to ensuring this works. interfaces with the ui.

public class Timer2 : MonoBehaviour
{
    public static float TimerValue = 120;   // initial timer value
    Text timer;

    // Use this for initialization
    void Start()
    {
        timer = GetComponent<Text>();
    }

    // Update is called once per frame
    void Update()
    {
        timer.text = ": " + TimerValue;
        TimerValue = TimerValue - Time.deltaTime;
    }
}

此计时器解决方案的问题在于它将计时器显示为浮点数(见下图)。虽然在技术上功能正常,但它看起来真的很糟糕,而且数字会左右移动(由于数字的宽度不同),因此很难阅读。

如何四舍五入才能显示为整数?我环顾四周,只发现了双精度和十进制数据类型的舍入。我也不知道如何使用变量进行舍入,因为我尝试的所有示例都不适用于变量。理想情况下,我想继续使用 float,因为它更容易操作,而且我不需要小数 ro double 的细节。

由于您只关心浮点数的显示,而不是使用数字进行进一步计算,因此您可以只使用字符串的格式化功能 class。 例如,

timer.text = ": " + TimerValue.ToString("F2");

四舍五入,只显示小数点后两位。

timer.text = ": " + TimerValue.ToString("F0");

将四舍五入为整数。

Here's the documentation on the various formatting options available

您可以只使用string.Format来显示设置小数位数的值。

例如:

timer.text = string.Fomat(": {0:0}", TimerValue);    // format with 0 decimal places
// output
// : 118

timer.text = string.Fomat(": {0:0.00}", TimerValue);    // format with 2 decimal places
// output
// : 117.97

请注意,这将向上舍入值。