.NET에서 숫자의 "st", "nd", "rd" 및 "th" 끝을 얻는 쉬운 방법이 있습니까?[복제하다]

StackOverflow https://stackoverflow.com/questions/69262

문제

이 질문에는 이미 답변이 있습니다.

다음을 변환하기 위해 .NET에서 누락된 메서드나 형식 문자열이 있는지 궁금합니다.

   1 to 1st
   2 to 2nd
   3 to 3rd
   4 to 4th
  11 to 11th
 101 to 101st
 111 to 111th

이 링크 자신만의 함수를 작성하는 데 관련된 기본 원칙에 대한 나쁜 예가 있지만 제가 놓친 내장 용량이 있는지 더 궁금합니다.

해결책

Scott Hanselman의 답변은 질문에 직접 답변하기 때문에 허용되는 답변입니다.

그러나 해결 방법은 다음을 참조하세요. 이 훌륭한 답변.

도움이 되었습니까?

해결책

아니요, .NET 기본 클래스 라이브러리에는 내장된 기능이 없습니다.

다른 팁

생각보다 매우 간단한 기능입니다.이를 위한 .NET 함수가 이미 존재할 수도 있지만 다음 함수(PHP로 작성됨)가 해당 작업을 수행합니다.그것을 이식하는 것이 너무 어렵지 않아야합니다.

function ordinal($num) {
    $ones = $num % 10;
    $tens = floor($num / 10) % 10;
    if ($tens == 1) {
        $suff = "th";
    } else {
        switch ($ones) {
            case 1 : $suff = "st"; break;
            case 2 : $suff = "nd"; break;
            case 3 : $suff = "rd"; break;
            default : $suff = "th";
        }
    }
    return $num . $suff;
}

@nickf:C#의 PHP 함수는 다음과 같습니다.

public static string Ordinal(int number)
{
    string suffix = String.Empty;

    int ones = number % 10;
    int tens = (int)Math.Floor(number / 10M) % 10;

    if (tens == 1)
    {
        suffix = "th";
    }
    else
    {
        switch (ones)
        {
            case 1:
                suffix = "st";
                break;

            case 2:
                suffix = "nd";
                break;

            case 3:
                suffix = "rd";
                break;

            default:
                suffix = "th";
                break;
        }
    }
    return String.Format("{0}{1}", number, suffix);
}

간단하고 깨끗하며 빠릅니다.

    private static 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";
    }

또는 더 나은 방법은 확장 방법으로

public static class IntegerExtensions
{
    public static string DisplayWithSuffix(this int num)
    {
        if (num.ToString().EndsWith("11")) return num.ToString() + "th";
        if (num.ToString().EndsWith("12")) return num.ToString() + "th";
        if (num.ToString().EndsWith("13")) return num.ToString() + "th";
        if (num.ToString().EndsWith("1")) return num.ToString() + "st";
        if (num.ToString().EndsWith("2")) return num.ToString() + "nd";
        if (num.ToString().EndsWith("3")) return num.ToString() + "rd";
        return num.ToString() + "th";
    }
}

이제 전화만 하면 돼요

int a = 1;
a.DisplayWithSuffix(); 

또는 심지어는 직접적으로

1.DisplayWithSuffix();

이 내용은 이미 다루었지만 링크하는 방법을 잘 모르겠습니다.코드 조각은 다음과 같습니다.

    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";
        }
    }

참고:이것은 확장 방법입니다..NET 버전이 3.5 미만인 경우 this 키워드를 제거하세요.

[편집하다]:잘못된 점을 지적해 주셔서 감사합니다. 코드 복사/붙여넣기를 통해 얻을 수 있는 정보입니다. :)

Microsoft SQL Server 함수 버전은 다음과 같습니다.

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의 질문에 대한 답변이 아니라는 것을 알고 있지만 이 스레드에서 SQL Server 함수를 리프트하는 것이 유용하다는 것을 알았기 때문에 여기에 해당하는 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;

..., -1st, 0th가 의미가 있나요?

public static string OrdinalSuffix(int ordinal)
{
    //Because negatives won't work with modular division as expected:
    var abs = Math.Abs(ordinal); 

    var lastdigit = abs % 10; 

    return 
        //Catch 60% of cases (to infinity) in the first conditional:
        lastdigit > 3 || lastdigit == 0 || (abs % 100) - lastdigit == 10 ? "th" 
            : lastdigit == 1 ? "st" 
            : lastdigit == 2 ? "nd" 
            : "rd";
}

또 다른 맛:

/// <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";
            }
        }
    }
}
else if (choice=='q')
{
    qtr++;

    switch (qtr)
    {
        case(2): strcpy(qtrs,"nd");break;
        case(3):
        {
           strcpy(qtrs,"rd");
           cout<<"End of First Half!!!";
           cout<<" hteam "<<"["<<hteam<<"] "<<hs;
           cout<<" vteam "<<" ["<<vteam;
           cout<<"] ";
           cout<<vs;dwn=1;yd=10;

           if (beginp=='H') team='V';
           else             team='H';
           break;
       }
       case(4): strcpy(qtrs,"th");break;

서수형 접미사는 구하기 힘든 것 같아요...기본적으로 스위치를 사용하여 숫자를 테스트하고 접미사를 추가하는 함수를 작성해야 합니다.

특히 특정 로케일인 경우 언어가 이를 내부적으로 제공할 이유가 없습니다.

작성할 코드의 양에 관해서는 해당 링크보다 조금 더 잘할 수 있지만 이를 위해서는 함수를 코딩해야 합니다...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top