본문 바로가기

Unity

[Unity] 숫자 단위(K,M,B) 로 바꾸기

입력 숫자를 단위에 따라 변환.

K - 1,000

M - 1,000,000

B - 1,000,000,000

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NumberTest : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("1,000 => " + ChangeNumber("1000"));
        Debug.Log("123,456 => " + ChangeNumber("123456"));
        Debug.Log("1,000,000 => " + ChangeNumber("1000000"));
        Debug.Log("1,000,000,000 => " + ChangeNumber("1000000000"));
    }

    public static string ChangeNumber(string number)
    {
        char[] unitAlphabet = new char[3] { 'K', 'M', 'B' };
        int unit = 0;
        while (number.Length > 6)
        {
            unit++;
            number = number.Substring(0, number.Length - 3);
        }
        if (number.Length > 3)
        {
            int newInt = int.Parse(number);
            if (number.Length > 4)
            {
                return (newInt / 1000).ToString() + unitAlphabet[unit];
            }
            else
            {
                return (newInt / 1000f).ToString("0.0") + unitAlphabet[unit];
            }
        }
        else
        {
            int newInt = int.Parse(number);
            return (newInt).ToString();
        }
    }
}

 

결과