What is a more elegant way of showing N significant digits of a calculation?
-
23-07-2021 - |
Domanda
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.
Soluzione
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);
Altri suggerimenti
Convert (x % 1000000) to string, where % stands for modulo operation.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow