简体   繁体   中英

string.Format to display only first n (2) digits in a number

I have a mouse move coordinate,

For example:

s = string.Format("{0:D4},{1:D4}", nx, ny);

the result s is "0337,0022"

the question is how to show only two digits in front only?

I would like to get:

s is "03,00"

Here is another example:

s = "0471,0306"

I want to be:

s = "04,03"

and when the coordinate is "-"

example

s = "-0471,0306"

I want to be:

s = "-04,03"
s =string.Format("{0},{1}",  
                 string.Format("{0:D4}", nx).Substring(0,2), 
                 string.Format("{0:D4}", ny).Substring(0,2));

Just split the string on the comma and then sub-string the first two characters of each portion, like this:

string result = String.Empty;
string s = String.Format("{0:D4},{1:D4}", nx, ny);
string[] values = s.Split(',');

int counter = 0;
foreach (string val in values)
{
    StringBuilder sb = new StringBuilder();
    int digitsCount = 0;

    // Loop through each character in string and only keep digits or minus sign
    foreach (char theChar in val)
    {
        if (theChar == '-')
        {
            sb.Append(theChar);
        }

        if (Char.IsDigit(theChar))
        {
            sb.Append(theChar);
            digitsCount += 1;
        }

        if (digitsCount == 2)
        {
            break;
        }
    }

    result += sb.ToString();

    if (counter < values.Length - 1)
    {
        result += ",";
    }

    counter += 1;
}

Note: This will work for any amount of comma separated values you have in your s string.

I'd do it this way:

Func<int, string> f = n => n.ToString("D4").Substring(0, 2);
var s = string.Format("{0},{1}", f(nx), f(ny));

Check the number before you use Substring.

        var s1 = nx.ToString();
        var s2 = ny.ToString();
        // Checks if the number is long enough
        string c1 = (s1.Count() > 2) ? s1.Substring(0, 2) : s1;
        string c2 = (s2.Count() > 2) ? s2.Substring(0, 2) : s2;
        Console.WriteLine("{0},{1}",c1,c2);

Assuming that nx and ny are integers

s = nx.ToString("D4").Substring(0,2)        // leftmost digits
  + ny.ToString("D4").Substring(0,2)        // leftmost digits

"D4" ensure the size of the string that must be enought for substring boundaries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM