Skip to content

Instantly share code, notes, and snippets.

@chiliec
Created November 30, 2017 08:53
Show Gist options
  • Save chiliec/22e34af2d08a964fc1418908a19b0c15 to your computer and use it in GitHub Desktop.
Save chiliec/22e34af2d08a964fc1418908a19b0c15 to your computer and use it in GitHub Desktop.
Склонение числительных в golang
func declOfNum(number int, titles []string) string {
cases := []int{2, 0, 1, 1, 1, 2}
var currentCase int
if number % 100 > 4 && number % 100 < 20 {
currentCase = 2
} else if number % 10 < 5 {
currentCase = cases[number%10]
} else {
currentCase = cases[5]
}
return titles[currentCase]
}
titles := []string{"фотография", "фотографии", "фотографий"}
number := 1
declOfNum(number, titles)
@azalio
Copy link

azalio commented Jun 24, 2022

@MashinaMashina
Copy link

MashinaMashina commented Nov 24, 2022

С поддержкой отрицательных чисел:
https://go.dev/play/p/RZItGDnRHYo

func declOfNum(number int, titles []string) string {
	if number < 0 {
		number *= -1
	}

	cases := []int{2, 0, 1, 1, 1, 2}
	var currentCase int
	if number%100 > 4 && number%100 < 20 {
		currentCase = 2
	} else if number%10 < 5 {
		currentCase = cases[number%10]
	} else {
		currentCase = cases[5]
	}
	return titles[currentCase]
}

func main() {
	titles := []string{"день", "дня", "дней"}

	fmt.Println(1, declOfNum(1, titles))
	fmt.Println(2, declOfNum(2, titles))
	fmt.Println(5, declOfNum(5, titles))
	fmt.Println(-1, declOfNum(-1, titles))
	fmt.Println(-2, declOfNum(-2, titles))
	fmt.Println(-5, declOfNum(-5, titles))

}

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