Question

I created the following function to show the last six significant digits of a number:

private static string ShowSigDigits(long n, int sig)
{
    string[] arr1 = n.ToString().Select(c => c.ToString()).ToArray();

    // reverse the array of string characters 
    Array.Reverse(arr1);
    List<string> stringList = new List<string>();

    for (int x = 0; x < arr1.Length; x++)
    {
        // get the last sig significant digits (loop is zero-based)
        if (x <= sig-1)
        {
            stringList.Add(arr1[x]);
        }
    }

    stringList.Reverse();

    return(string.Join("", stringList.ToArray()));
}

For example, entering 182736734,6 would result in 736734.

I'm sure there's a more efficient way of doing this, and would like some suggestions.

Thanks.

Was it helpful?

Solution

There are many different ways to do this - Substring is one of the first to come to mind (as does the VB.NET Strings.Right).

string nString = n.ToString();
return nString.Substring(nString.Length - sig);

OTHER TIPS

Convert (x % 1000000) to string, where % stands for modulo operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top