c# - 在 C# 中格式化大数

标签 c# unity3d formatting

我正在使用 Unity 制作一个“增量游戏”,也称为“空闲游戏”,我正在尝试格式化大数字。例如,当 gold 达到 1000 或更多时,它将显示为 Gold: 1k 而不是 Gold: 1000

using UnityEngine;
using System.Collections;

public class Click : MonoBehaviour {

    public UnityEngine.UI.Text GoldDisplay;
    public UnityEngine.UI.Text GPC;
    public double gold = 0.0;
    public int gpc = 1;

    void Update(){
        GoldDisplay.text = "Gold: " +  gold.ToString ("#,#");
        //Following is attempt at changing 10,000,000 to 10.0M
        if (gold >= 10000000) {
        GoldDisplay.text = "Gold: " + gold.ToString ("#,#M");
        }
        GPC.text = "GPC: " + gpc;
    }

    public void Clicked(){
            gold += gpc;
    }
}

我在网上搜索时尝试了其他示例,这是 gold.ToString ("#,#"); 的来源,但没有一个有效。

最佳答案

轻微重构:

public static string KMBMaker( double num )
{
    double numStr;
    string suffix;
    if( num < 1000d )
    {
        numStr = num;
        suffix = "";
    }
    else if( num < 1000000d )
    {
        numStr = num/1000d;
        suffix = "K";
    }
    else if( num < 1000000000d )
    {
        numStr = num/1000000d;
        suffix = "M";
    }
    else
    {
        numStr = num/1000000000d;
        suffix = "B";
    }
    return numStr.ToString() + suffix;
}

用途:

GoldDisplay.text = KMBMaker(gold);

变化:

  1. 显式使用 double 常量
  2. 删除重复项
  3. 单独关注 - 此方法无需了解文本框

关于c# - 在 C# 中格式化大数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30992304/

相关文章:

c# - Outlook Mapi 访问共享联系人

c# - 无法将 enum 转换为 int dot42

c# - Html.CheckBoxFor 所需的复选框验证工作相反

c# - `Aggregate`怎么写成 `from .. in ..`?

ios - Unity3D - 解析迁移

c# - 如何正确地继续将多个脚本添加到游戏对象

c# - 在继承中使用 this() 和 base()

asp.net-mvc - 日期格式不正确的 MVC DateTime 绑定(bind)

asp.net - Visual Studio 2008 将 asp 标签格式化为小写

javascript - 在此代码中将日期格式化为 dd/MM/yyyy