Search code examples
c#string-formatting

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"

Solution

  • 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.