Unity格式化多个数字

using System.IO;
using System;

class Program
{
    // Very simple example, gonna throw exception for numbers bigger than 10^12
    static readonly string[] suffixes = {"", "k", "M", "G"};
    static string prettyCurrency(long cash, string prefix="$")
    {
        int k;
        if(cash == 0)
            k = 0;    // log10 of 0 is not valid
        else
            k = (int)(Math.Log10(cash) / 3); // get number of digits and divide by 3
        var dividor = Math.Pow(10,k*3);  // actual number we print
        var text = prefix + (cash/dividor).ToString("F1") + suffixes[k];
        return text;
    }

    static void Main()
    {
        Console.WriteLine(prettyCurrency(0));
        Console.WriteLine(prettyCurrency(333));
        Console.WriteLine(prettyCurrency(3145));
        Console.WriteLine(prettyCurrency(314512455));
        Console.WriteLine(prettyCurrency(31451242545));
    }
}

$0.0
$333.0
$3.1k
$314.5M
$31.5G

留下评论

邮箱地址不会被公开。 必填项已用*标注