Skip to content

Instantly share code, notes, and snippets.

@Chigozie-Gerald
Created September 14, 2022 07:48
Show Gist options
  • Save Chigozie-Gerald/40fc0c8447c42f0bab5954cc86a77b7a to your computer and use it in GitHub Desktop.
Save Chigozie-Gerald/40fc0c8447c42f0bab5954cc86a77b7a to your computer and use it in GitHub Desktop.
Script to get text in Lithuanian language from a number (Javascript)
// According to https://gist.github.com/tadas-subonis/6e23811db350a440cd47e2e5dd40e2cb
const numToText = (num) => {
const units = [
"",
"vienas",
"du",
"trys",
"keturi",
"penki",
"šeši",
"septyni",
"aštuoni",
"devyni",
];
const subTen = [
"",
"vienuolika",
"dvylika",
"trylika",
"keturiolika",
"penkiolika",
"šešiolika",
"septyniolika",
"aštuoniolika",
"devyniolika",
];
const tens = [
"",
"dešimt",
"dvidešimt",
"trisdešimt",
"keturiasdešimt",
"penkiasdešimt",
"šešiasdešimt",
"septyniasdešimt",
"aštuoniasdešimt",
"devyniasdešimt",
];
const numWord = [
["milijonas", "milijonai", "milijonų"],
["tūkstantis", "tūkstančiai", "tūkstančių"],
];
if (num < 0 || num >= 10 ** 9) {
/* If number is less than zero or greater or equal to a billion,
return a stringified text of the number
*/
return `${num}`;
} else {
const strInt_num = `${parseInt(`${num}`)}`; // Stringify the number
const len = 9 - strInt_num.length;
const numOfZeros = Math.sign(len) === 1 ? len : 0;
// Precede the number by zeros until the length of the string is 9
const formatted = `${"0".repeat(numOfZeros)}${strInt_num}`;
// Split the 9 characters long string above into 3 arrays.
// Each array has a string with a length of 3
const numTripletArray = formatted.split(/(.{3})/g).filter((N) => N);
const numSet = [];
numTripletArray.forEach((triplet, n) => {
num = parseInt(triplet) || 0;
let numCase = 0;
const hundDiv = Math.floor(num / 100);
if (hundDiv > 0) {
if (hundDiv > 1) {
numSet.push(units[hundDiv]);
}
numSet.push(hundDiv > 1 ? "šimtai" : "šimtas");
}
// Example: If num = is 197
const subHundNum = num % 100; // Becomes 97
const tensValue = Math.floor(subHundNum / 10); // Becomes 9
const unitValue = subHundNum % 10; // Becomes 7
if (10 < subHundNum && subHundNum < 20) {
// If num is between 10 and 20
numSet.push(subTen[unitValue]);
numCase = 2;
} else {
// Num that is greater than or equal to 20
if (tensValue > 0) {
// If there is a tens value
numSet.push(tens[tensValue]);
}
if (unitValue > 0) {
// If there is a unit value
numSet.push(units[unitValue]);
numCase = unitValue > 1 ? 1 : 0;
} else {
numCase = 2;
}
}
if (n < numWord.length && triplet !== "000") {
numSet.push(numWord[n][numCase]);
}
});
let number = numSet.join(" ").trim();
number = number.replace(" ", " ");
return number;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment