[英]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" 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.注意:这适用于您在s
字符串中的任意数量的逗号分隔值。
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.在使用 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假设 nx 和 ny 是整数
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 “D4”确保字符串的大小必须足够子字符串边界
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.