0
点赞
收藏
分享

微信扫一扫

Unity中实现四舍五入

佳简诚锄 2022-02-17 阅读 197

一:前言

C#中没有四舍五入,它采用的是四舍六入五成双,C#中的Math.Round和Unity中的Mathf.Round都是如此,想要实现四舍五入只能自己实现


二:代码实现

using UnityEngine;

/// <summary>
/// 数学相关工具类
/// </summary>
public static class MathUtils
{
    /// <summary>
    /// 四舍五入
    /// </summary>
    /// digits:保留几位小数
    public static float Round(float value, int digits = 1)
    {
        float multiple = Mathf.Pow(10, digits);
        float tempValue = value * multiple + 0.5f;
        tempValue = Mathf.FloorToInt(tempValue);
        return tempValue / multiple;
    }
}
举报

相关推荐

0 条评论