How to incline the word "day" by numbers?
There is a value of the difference between two dates in days.
How to make formatting in this form:
1 day, 2 days, 3 days, 4 days, 5 days, 20 days, etc.?
That is, what would change the words день
and дня
.
1
Author: default locale, 2017-09-14
2 answers
As suggested by default locale:
public String getDayAddition(int num) {
int preLastDigit = num % 100 / 10;
if (preLastDigit == 1) {
return "дней";
}
switch (num % 10) {
case 1:
return "день";
case 2:
case 3:
case 4:
return "дня";
default:
return "дней";
}
}
3
Author: Tsyklop, 2020-04-02 14:36:46
I just wrote a universal decliner for different words, of course, if a word is added, then you need to describe three types of endings yourself: 0 array index - 1 unit, 101 units 1 array index - 2 units, 102 units 2 array index - 5 units, 11 units, 26 units, 10011 units. To do this, I attach three classes: util, enum, test with processing of two words: day and month
Utility:
public class WordDeclensionUtil {
/**
* Получить слово в склонении в зависимости от переданного числа, например, для WordDeclensionEnum.MONTH
* 11 месяцEВ
* 21 месяц
*/
public static String getWordInDeclension(WordDeclensionEnum wordType, int n) {
// смотрим две последние цифры
int result = n % 100;
if (result >=10 && result <= 20) {
// если окончание 11 - 20
return wordType.getDeclensions()[2];
}
// смотрим одну последнюю цифру
result = n % 10;
if (result == 0 || result > 4) {
return wordType.getDeclensions()[2];
}
if (result > 1) {
return wordType.getDeclensions()[1];
} if (result == 1) {
return wordType.getDeclensions()[0];
}
return null;
}
}
Enumeration:
@Getter
@AllArgsConstructor
public enum WordDeclensionEnum {
MONTH(new String[]{"месяц", "месяца", "месяцев"}),
DAY(new String[]{"день", "дня", "дней"}),
;
/**
* Склонения в зависимо от переданного количества единиц сущности.
* Минимальный размер: 3 склонения;
* index
* 0 - 1 единица, 101 единица
* 1 - 2 единицы, 102 единицы
* 2 - 5 единиц, 11 единиц, 26 единиц
*/
private String[] declensions;
}
Test to check the endings of words before running the project:
class WordDeclensionUtilTest {
@Test
void getWordInDeclension() {
int countTestCases = 9;
int[] count = {1, 2, 5, 10, 19, 1001, 1011, 10006, 202};
@SuppressWarnings("unchecked")
TwoFieldDto<WordDeclensionEnum, String[]>[] words = new TwoFieldDto[]{
new TwoFieldDto<>(WordDeclensionEnum.MONTH, new String[]{"месяц", "месяца", "месяцев", "месяцев", "месяцев", "месяц", "месяцев", "месяцев", "месяца"}),
new TwoFieldDto<>(WordDeclensionEnum.DAY, new String[]{"день", "дня", "дней", "дней", "дней", "день", "дней", "дней", "дня"}),
};
for (int i = 0; i < countTestCases; i++) {
for (int j = 0; j < words.length; j++) {
String wordInDeclension = WordDeclensionUtil.getWordInDeclension(words[j].getKey(), count[i]);
assertEquals(words[j].getValue()[i], wordInDeclension, String.format("declension not equal: i = %s, j=%s", i, j));
}
}
}
}
0
Author: Дима Годиков, 2020-06-02 10:36:49