هل هناك طريقة سهلة في .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

هذا الرابط يحتوي على مثال سيء للمبدأ الأساسي الذي يتضمنه كتابة وظيفتك الخاصة، لكنني أشعر بالفضول أكثر إذا كانت هناك قدرة داخلية أفتقدها.

حل

إجابة سكوت هانسيلمان هي الإجابة المقبولة لأنها تجيب على السؤال مباشرة.

ولكن للحصول على حل، انظر هذه الإجابة العظيمة.

هل كانت مفيدة؟

المحلول

لا، لا توجد إمكانية مضمنة في مكتبة .NET Base Class.

نصائح أخرى

إنها وظيفة أبسط بكثير مما تعتقد.على الرغم من أنه قد تكون هناك وظيفة .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;
}

@نيكف:هذه هي وظيفة PHP في C#:

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، فما عليك سوى إزالة الكلمة الأساسية هذه

[يحرر]:شكرًا للإشارة إلى أن هذا غير صحيح، وهذا ما تحصل عليه مقابل نسخ/لصق الكود :)

إليك إصدار وظيفة 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 من هذا الموضوع، إليك ما يعادل دلفي (باسكال):

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، 0 منطقي؟

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