Reputation: 1287
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"
Upvotes: 1
Views: 6736
Reputation: 95
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
Upvotes: 1
Reputation: 34846
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.
Upvotes: 2
Reputation: 2311
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);
Upvotes: 0
Reputation: 117029
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));
Upvotes: 0
Reputation: 63065
s =string.Format("{0},{1}",
string.Format("{0:D4}", nx).Substring(0,2),
string.Format("{0:D4}", ny).Substring(0,2));
Upvotes: 3