unity笔记_四舍六入五成双

 float Round(float num, int length)//0.58
    {

        string str = num.ToString();
        //传入整数,没有小数点
        if (!str.Contains("."))
        {
            return num;
        }
        else //有小数点
        {
            float _num = Mathf.Abs(num);
            float temp = _num * Mathf.Pow(10, length + 1);
            float rem = temp % 10f; //和10取余  取个位数
            float res = temp / 10f;
            if ((int)rem <= 4) //舍掉
            {
                return ((int)res) / Mathf.Pow(10, length)*(num/ _num);
            }
            if ((int)rem >= 6) return ((int)(res + 1)) / Mathf.Pow(10, length);
            if ((int)rem == 5)
            {
                if (rem > 5) return ((int)(res + 1)) / Mathf.Pow(10, length) * (num / _num);
                else
                {
                    if (((int)(res % 10f)) % 2 == 0)
                        return ((int)res) / Mathf.Pow(10, length) * (num / _num);
                    else return ((int)(res + 1)) / Mathf.Pow(10, length) * (num / _num);
                }
            }
        }
        return num;
    }

猜你喜欢

转载自blog.csdn.net/weixin_60232873/article/details/122928392
今日推荐