【问题标题】:How to round float variables in C#如何在 C# 中舍入浮点变量
【发布时间】:2020-06-12 02:54:54
【问题描述】:

我正在用 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 的细节。

【问题讨论】:

标签: c# unity3d timer rounding


【解决方案1】:

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

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

将四舍五入,只显示到小数点后 2 位。

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

将其四舍五入为整数。

Here's the documentation on the various formatting options available

【讨论】:

    【解决方案2】:

    您可以只使用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
    

    请注意,这会将值四舍五入。

    【讨论】:

      猜你喜欢
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      相关资源
      最近更新 更多