Skip to content

Instantly share code, notes, and snippets.

@KANekT
Created May 3, 2018 13:02
Show Gist options
  • Save KANekT/1e2953f8c75dd9a2994c64c1711d7157 to your computer and use it in GitHub Desktop.
Save KANekT/1e2953f8c75dd9a2994c64c1711d7157 to your computer and use it in GitHub Desktop.
Склонение числительных в C#
public class DeclensionGenerator
{
/// <summary>
/// Возвращает слова в падеже, зависимом от заданного числа
/// </summary>
/// <param name="number">Число от которого зависит выбранное слово</param>
/// <param name="nominativ">Именительный падеж слова. Например "день"</param>
/// <param name="genetiv">Родительный падеж слова. Например "дня"</param>
/// <param name="plural">Множественное число слова. Например "дней"</param>
/// <returns></returns>
public static string Generate(int number, string nominativ, string genetiv, string plural) {
var titles = new[] {nominativ, genetiv, plural};
var cases = new[] {2, 0, 1, 1, 1, 2};
return titles[number % 100 > 4 && number % 100 < 20 ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]];
}
}
@Andrewmad
Copy link

Отлично!

@KotM
Copy link

KotM commented Feb 7, 2023

It is genius, thanks!

Small update to make this approach more universal and working both in RU and EN locales:

        public static string NumDeclension(int number, string nominative, string plural, string genitive = null)
        {
            if (string.IsNullOrEmpty(genitive))
            {
                return number == 1 ? nominative : plural;
            }

            var titles = new[] { nominative, genitive, plural };
            var cases = new[] { 2, 0, 1, 1, 1, 2 };
            return titles[number % 100 > 4 && number % 100 < 20 ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]];
        }

In this case if genitive is omitted or empty, so simplest declination will be used, like in English. It makes this method to be working in mixed text generation locales without additional verifications.

Please note, I've changed parameters order to make one of them optional.

@FozerG
Copy link

FozerG commented Mar 17, 2023

мне кажется нужно быть ученым что бы такое сделать

@ivanmem
Copy link

ivanmem commented Dec 11, 2023

Есть ли аналогичная функция для чисел с плавающей запятой?

@KotM
Copy link

KotM commented Dec 12, 2023

Есть ли аналогичная функция для чисел с плавающей запятой?

Например? 2.5 яблока. 2.1 яблока. 2.4456 яблока. Зачем тут может потребоваться какое-то склонение?

@ivanmem
Copy link

ivanmem commented Dec 12, 2023

1 яблоко, 1.5 яблока

@FozerG
Copy link

FozerG commented Dec 12, 2023

1 яблоко, 1.5 яблока

Проверяешь если целое число - используешь способ выше, если float то используешь слово множественного числа

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment