Unity中实现大数单位转换

584 阅读1分钟

一:前言


很多游戏中的数据涉及到很大的数字,比如当前升级需要310000000000金币,总不能把310000000000这个数字显示在屏幕上,所以就引入了一些大数据数字的单位转换
K是10的3次方,也就是千
M是10的6次方,也就是百万
B是10的9次方,也就是十亿
T是10的12次方,也就是万亿


二:代码实现

using UnityEngine;

/// <summary>
/// 字符串工具类
/// </summary>
public static class StringUtils
{
    //一般是单独配一个单位表 读表获取
    static string[] unitList = new string[] { "", "K", "M" };

    /// <summary>
    /// 格式化货币
    /// </summary>
    /// digit:保留几位小数
    public static string FormatCurrency(long num, int digit = 1)
    {
        float tempNum = num;
        long v = 1000;//几位一个单位
        int unitIndex = 0;
        while (tempNum >= v)
        {
            unitIndex++;
            tempNum /= v;
        }

        string str = "";
        if (unitIndex >= unitList.Length)
        {
            Debug.LogError("超出单位表中的最大单位");
            str = num.ToString();
        }
        else
        {
            tempNum = Round(tempNum, digit);
            str = $"{tempNum}{unitList[unitIndex]}";
        }
        return str;
    }

    /// <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;
    }
}