public static string Ordinal(this int number)
{
var ones = number % 10;
var tens = Math.Floor (number / 10f) % 10;
if (tens == 1)
{
return number + "th";
}
switch (ones)
{
case 1: return number + "st";
case 2: return number + "nd";
case 3: return number + "rd";
default: return number + "th";
}
}
CREATE FUNCTION [Internal].[GetNumberAsOrdinalString]
(
@num int
)
RETURNS nvarchar(max)
AS
BEGIN
DECLARE @Suffix nvarchar(2);
DECLARE @Ones int;
DECLARE @Tens int;
SET @Ones = @num % 10;
SET @Tens = FLOOR(@num / 10) % 10;
IF @Tens = 1
BEGIN
SET @Suffix = 'th';
END
ELSE
BEGIN
SET @Suffix =
CASE @Ones
WHEN 1 THEN 'st'
WHEN 2 THEN 'nd'
WHEN 3 THEN 'rd'
ELSE 'th'
END
END
RETURN CONVERT(nvarchar(max), @num) + @Suffix;
END
我知道这不是 OP 问题的答案,但是因为我发现从这个线程提取 SQLServer 函数很有用,所以这里有一个 Delphi (Pascal)等价物:
function OrdinalNumberSuffix(const ANumber: integer): string;
begin
Result := IntToStr(ANumber);
if(((Abs(ANumber) div 10) mod 10) = 1) then // Tens = 1
Result := Result + 'th'
else
case(Abs(ANumber) mod 10) of
1: Result := Result + 'st';
2: Result := Result + 'nd';
3: Result := Result + 'rd';
else
Result := Result + 'th';
end;
end;
private static string GetOrdinalSuffix(int num)
{
string number = num.ToString();
if (number.EndsWith("11")) return "th";
if (number.EndsWith("12")) return "th";
if (number.EndsWith("13")) return "th";
if (number.EndsWith("1")) return "st";
if (number.EndsWith("2")) return "nd";
if (number.EndsWith("3")) return "rd";
return "th";
}
或者更好的是,作为一种扩展方法
public static class IntegerExtensions
{
public static string DisplayWithSuffix(this int num)
{
string number = num.ToString();
if (number.EndsWith("11")) return number + "th";
if (number.EndsWith("12")) return number + "th";
if (number.EndsWith("13")) return number + "th";
if (number.EndsWith("1")) return number + "st";
if (number.EndsWith("2")) return number + "nd";
if (number.EndsWith("3")) return number + "rd";
return number + "th";
}
}
/// <summary>
/// Extension methods for numbers
/// </summary>
public static class NumericExtensions
{
/// <summary>
/// Adds the ordinal indicator to an integer
/// </summary>
/// <param name="number">The number</param>
/// <returns>The formatted number</returns>
public static string ToOrdinalString(this int number)
{
// Numbers in the teens always end with "th"
if((number % 100 > 10 && number % 100 < 20))
return number + "th";
else
{
// Check remainder
switch(number % 10)
{
case 1:
return number + "st";
case 2:
return number + "nd";
case 3:
return number + "rd";
default:
return number + "th";
}
}
}
}