有一个简单的方法来创建在C#中序? [英] Is there an easy way to create ordinals in C#?
问题描述
有没有在C#一个简单的方法来创建序数了解多少?例如:
Is there an easy way in C# to create Ordinals for a number? For example:
- 在1月1日返回
- 2的回报2号
- 3返回3
- ...等
这可以通过的String.Format做()
还是有可做到这一点的任何功能?
Can this be done through String.Format()
or are there any functions available to do this?
推荐答案
本页面为您提供了所有的自定义数字格式规则的完整列表:
This page gives you a complete listing of all custom numerical formatting rules:
<一个href="http://msdn.microsoft.com/en-us/library/0c899ak8.aspx">http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
正如你所看到的,没有什么在那里大约序,所以无法使用的String.Format完成。但它不是真的那么难写一个函数来做到这一点。
As you can see, there is nothing in there about ordinals, so it can't be done using String.Format. However its not really that hard to write a function to do it.
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";
}
}
更新:从技术上讲序数不为&LT存在; = 0,所以我已经更新上面的code。另外去掉了多余的ToString()方法。
Update: Technically Ordinals don't exist for <= 0, so I've updated the code above. Also removed the redundant ToString() methods.
另外请注意,这不是国际化。我不知道是什么序看起来像在其他语言中。
Also note, this is not internationalised. I've no idea what ordinals look like in other languages.
这篇关于有一个简单的方法来创建在C#中序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!