在 C# 中是否有一种简单的方法可以为数字创建序数?例如:
Is there an easy way in C# to create Ordinals for a number? For example:
- 1 返回第一个
- 2 返回第二个
- 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:
自定义数字格式字符串
如您所见,其中没有关于序数的内容,因此无法使用 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"; } }更新:从技术上讲,<= 0 不存在序数,所以我更新了上面的代码.还删除了多余的 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 internationalized. I've no idea what ordinals look like in other languages.
更多推荐
有没有一种简单的方法可以在 C# 中创建序数?
发布评论