Home > Back-end >  How to save a very large number Unity
How to save a very large number Unity

Time:08-11

I'm making an andoid game (clicker) on Unity. 1 500 321 stored as Millions = 1, Thousands = 500, Hundreds = 3, dozens = 2, units = 1. I have a main script that stores a number (code 1) and a script that reduces this number (code 2) (those were 100,000 became 1K). How to store a number that can reach 100 zeros so as not to heavily rewrite code 2 and it would be nice to be able to store the number (money) in PlayerPrefs ? Thanks in advance!

code 1:

public Text moneyText;

public int money;
public int moneyPerClick = 1000000;

void Start()
{
    money = PlayerPrefs.GetInt("money");
    moneyPerClick = PlayerPrefs.GetInt("moneyPerClick");
}

void Update()
{
    moneyText.text = FormatNumbers.formatNumber(money);
}


public void Clik()
{
    money  = moneyPerClick;
    PlayerPrefs.SetInt("money", money);
}

code 2:

public static class FormatNumbers
{

public static string[] format_name = new[]
{
    "", "K", "M", "t", "q", "Q", "s", "S", "o", "n", "d", "U", "D", "T", 
 "Qt", "Qd", "Sd", "St", "O", "N", "v", "c"
};

public static string formatNumber(float num)
{
    if (num == 0)
        return "0";

    int i = 0;
    while(i 1 < format_name.Length && num >= 1000f)
    {
        num /= 1000f;
        i  ;
    }
    return num.ToString("#.##")   format_name[i];
}

CodePudding user response:

Use BigInteger, it supports arbitrary large numbers. It has methods to convert it to a byte-array, and a constructor to convert back again.

An alternative could be to use a double, this has sufficient range, but cannot represent all integers within its range exactly. But this should mostly be a problem if you are adding a very small number to a very large number, so may or may not be appropriate for your use case.

In general you want to use a single representation of your values, and convert it to human readable format as late as possible.

CodePudding user response:

You need to use System.Numerics.BigInteger add it to your project you need to use special functions for the operations like BigInteger.Add(HERE A BIG INTEGER, HERE A BIG INTEGER) for storing the data you need to convert BigInteger to string with .ToString() and then store as string For reading it again BigInteger.Parse(HERE STRING)

  • Related