package ClasAndMain;
public class NumberToPersianWords {
private static final String[] ONES = {"", "یک", "دو", "سه", "چهار", "پنج", "شش", "هفت", "هشت", "نه", "ده",
"یازده", "دوازده", "سیزده", "چهارده", "پانزده", "شانزده", "هفده", "هجده", "نوزده"};
private static final String[] TENS = {"", "ده", "بیست", "سی", "چهل", "پنجاه", "شصت", "هفتاد", "هشتاد", "نود"};
private static final String[] HUNDREDS = {"", "صد", "دویست", "سیصد", "چهارصد", "پانصد", "ششصد", "هفتصد", "هشتصد", "نهصد"};
private static final String[] ORDERS = {"", "هزار", "میلیون", "میلیارد", "بیلیون", "بیلیارد", "تریلیون", "تریلیارد", "کوآدریلیون", "کادریلیارد", "کوینتیلیون", "کوانتینیارد", "سکستیلیون", "سکستیلیارد", "سپتیلیون", "سپتیلیارد", "اکتیلیون", "اکتیلیارد", "نانیلیون", "نانیلیارد"};
public static String convertToWords(long number) {
if (number == 0) {
return "صفر";
}
if (number < 0) {
return "منفی " + convertToWords(Math.abs(number));
}
String words = "";
int orderIndex = 0;
while (number > 0) {
long currentNumber = number % 1000;
String currentWords = "";
int hundredsDigit = (int) currentNumber / 100;
if (hundredsDigit > 0) {
currentWords += HUNDREDS[hundredsDigit] + " و ";
}
int tensDigit = (int) (currentNumber % 100) / 10;
if (tensDigit > 1) {
currentWords += TENS[tensDigit] + " و ";
}
// Add a separate string for the 'and' before ten and add it to the final word
String separateAndForTens = "";
if (tensDigit == 1) {
separateAndForTens = "و";
}
int onesDigit = (int) currentNumber % 10;
if (tensDigit == 1 || onesDigit > 0) {
if (tensDigit == 1) {
currentWords += ONES[(int) (currentNumber % 100)];
} else {
currentWords += ONES[onesDigit];
}
}
if (currentNumber > 0) {
currentWords += " " + ORDERS[orderIndex] + " ";
}
// Add an 'and' before the first and last digits if needed
if (orderIndex == 0 && tensDigit > 0 && onesDigit > 0) {
words = separateAndForTens + words;
}
if (orderIndex > 0 && onesDigit > 0) {
int digitsCount = (int) Math.log10(currentNumber) + 1;
if (digitsCount >= 3) {
char lastDigit = String.valueOf(currentNumber).charAt(digitsCount - 1);
if (lastDigit != '0') {
currentWords = "و " + currentWords;
}
}
}
// Add an 'and' between numbers
if (orderIndex > 0 && words.trim().length() > 0) {
String lastWord = words.substring(words.lastIndexOf(" ") + 1);
if (!lastWord.equals("و")) {
words = words.trim() + " و ";
}
}
words = currentWords + words;
orderIndex++;
number = number / 1000;
}
// Add an 'and' before the last number if needed
if(words.lastIndexOf("و") != words.length() - 1) {
words = words + " و";
}
return words.trim();
}
public static boolean isPositiveNumber(String s) {
try {
long number = Long.parseLong(s);
return number >= 0;
} catch (NumberFormatException e) {
return false;
}
}
}