Search Unity

Format integer?

Discussion in 'Scripting' started by Bongmo, Jul 12, 2018.

  1. Bongmo

    Bongmo

    Joined:
    Jan 18, 2014
    Posts:
    155
    Hi.

    I have numbers like: 16345, 21550, 4366574, 16500220 etc.

    How can I fast change these numbers simply with coding to:
    16345 to 16000
    21550 to 21000
    4366574 to 4300000
    16500220 to 16000000

    I know how to do that with string formatting. Before I start to programming I wanted to know, how can I make it simpler.

    My thought is like that:
    Catch the first two digits from the integer. Then create a string. Add the two digits to the string and fill the rest with zeros.

    Thanks in advance.
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,195
    The typical approach to this is to divide by 10^N, then multiply by 10^N. Integers get truncated on division, so the remainder is lost. When you multiply again, you are essentially adding zeros.

    For example: 16345 / 1000 = 16; 16 * 1000 = 16000;

    In that case, the only real complexity is figuring out which number to divide by in each case, if your integers are dynamic. Log10 is one approach to that. Here's an implementation which lets you control how many digits to keep, defaulting to 2 like in your examples:

    Code (CSharp):
    1.         public static int ZeroifyInt(int value, int significantDigits = 2)
    2.         {
    3.             var formattedValue = value;
    4.  
    5.             var exponent = (int)Mathf.Log10(value) + 1 - significantDigits;
    6.             if (exponent > 0)
    7.             {
    8.                 var truncation = (int)Mathf.Pow(10, exponent);
    9.                 formattedValue /= truncation;
    10.                 formattedValue *= truncation;
    11.             }
    12.             return formattedValue;
    13.         }
    This results in values like this:

    16234 => 16000; 23450668 => 23000000; 123456 => 120000
     
    Last edited: Jul 12, 2018
    Brathnann and Bongmo like this.