我正在使用 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);
变化:
- 显式使用
double
常量 - 删除重复项
- 单独关注 - 此方法无需了解文本框
关于c# - 在 C# 中格式化大数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30992304/