有没有一种简单的方法可以在 C# 中创建序数?

编程入门 行业动态 更新时间:2024-10-19 13:32:29
本文介绍了有没有一种简单的方法可以在 C# 中创建序数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 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# 中创建序数?

本文发布于:2023-05-28 06:55:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/315124.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file &#039;D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!