使用十进制阈值将浮点数四舍五入为整数

时间:2020-07-08 14:19:25

标签: c# unity3d

我正在计算浮点数在变量中的时间,然后将浮点数转换为仅2个小数点,然后将其传递给字符串变量。但是,我不需要将浮点数转换为小数点,而是将浮点数舍入为整数。我该如何实现?

例如,如果计时器> 26.50f,则最终计时器应为27。

还可以手动设置阈值吗?阈值是小数点后的值吗?然后脚本决定整数属于哪个数字? 例如,我将阈值设置为.25至.99

float 1 = 23.26 = 24
float 2 = 17.25 = 18
float 3 = 19.24 = 19
public float timer;
public string timer_string;

void Update()
{
    timer += Time.deltaTime;
    timer_string = timer.ToString("F2"); //decimal upto 2 places
    timer_string = timer.ToString("F0"); //is this the way? Since it does not round up
}

2 个答案:

答案 0 :(得分:2)

要考虑的方法是利用现有的Math.Round(中点舍入为AwayFromZero),但是在舍入时(通过加/减)有效地转移了点。看起来像:

static double RoundBasedOnCustomThreshold(double number, double customThreshold = 0.25)
{
    // customThreshold of 1 will be equivalent to Math.Floor
    if (customThreshold <= 0 || customThreshold > 1)
        throw new ArgumentException();

    return Math.Round(number + 0.5 - customThreshold, 0, MidpointRounding.AwayFromZero);
}

通过添加0.5 - customThreshold,这很可能会以您想要的方式取整。

您可以在https://dotnetfiddle.net/OhUO3p使用一些输入值和结果。

答案 1 :(得分:1)

将下一个整数四舍五入称为“上限”,为Math.Ceiling。所以我怀疑你想要什么:

timer_string = Math.Ceiling(timer).ToString(...);

(供您选择格式...

如果您实际上是指其他一些舍入形式,请使用Math.Round(timer, MidpointRounding.YourChoiceHere)而不是Math.Ceiling;例如AwayFromZeroToPositiveInfinity