在c#中有一个简单的方法来创建一个数字的序数吗?例如:
1返回第1位 2返回第2 3返回第3 等
这是否可以通过String.Format()来完成,或者是否有可用的函数来完成?
在c#中有一个简单的方法来创建一个数字的序数吗?例如:
1返回第1位 2返回第2 3返回第3 等
这是否可以通过String.Format()来完成,或者是否有可用的函数来完成?
当前回答
我使用这个扩展类:
public static class Int32Extensions
{
public static string ToOrdinal(this int i)
{
return (i + "th")
.Replace("1th", "1st")
.Replace("2th", "2nd")
.Replace("3th", "3rd");
}
}
其他回答
你得自己动手了。在我的脑海中:
public static string Ordinal(this int number)
{
var work = number.ToString();
if ((number % 100) == 11 || (number % 100) == 12 || (number % 100) == 13)
return work + "th";
switch (number % 10)
{
case 1: work += "st"; break;
case 2: work += "nd"; break;
case 3: work += "rd"; break;
default: work += "th"; break;
}
return work;
}
你可以这样做
Console.WriteLine(432.Ordinal());
针对11/12/13例外进行了编辑。我确实从我的头顶说过:-)
为1011编辑-其他人已经修复了这个问题,只是想确保其他人不会抓取这个错误的版本。
根据其他答案:
public static string Ordinal(int n)
{
int r = n % 100, m = n % 10;
return (r<4 || r>20) && (m>0 && m<4) ? n+" stndrd".Substring(m*2,2) : n+"th";
}
本页为您提供了所有自定义数字格式规则的完整列表:
自定义数字格式字符串
如你所见,这里没有关于序数的内容,所以不能使用String.Format。然而,编写一个函数来实现它并不难。
public static string AddOrdinal(int num)
{
if( num <= 0 ) return num.ToString();
switch(num % 100)
{
case 11:
case 12:
case 13:
return num + "th";
}
switch(num % 10)
{
case 1:
return num + "st";
case 2:
return num + "nd";
case 3:
return num + "rd";
default:
return num + "th";
}
}
更新:从技术上讲,序数不存在<= 0,所以我更新了上面的代码。还删除了多余的ToString()方法。
还要注意,这不是国际化的。我不知道其他语言中的序数是什么样子。
记得国际化!
这里的解决方案只适用于英语。如果您需要支持其他语言,事情就会变得复杂得多。
例如,在西班牙语中,“1st”可以写成“1”。o”、“1。”、“1。o”或“1”。比如“取决于你数的东西是阳性、阴性还是复数!”
因此,如果您的软件需要支持不同的语言,请尽量避免使用序数。
这是dart中的实现,可以根据语言进行修改。
String getOrdinalSuffix(int num){
if (num.toString().endsWith("11")) return "th";
if (num.toString().endsWith("12")) return "th";
if (num.toString().endsWith("13")) return "th";
if (num.toString().endsWith("1")) return "st";
if (num.toString().endsWith("2")) return "nd";
if (num.toString().endsWith("3")) return "rd";
return "th";
}