NumToChar & CharToNum Util Functions

July 8, 2023

Util Functions

NumToChar & CharToNum Util Functions

Thuta Sann

Thuta Sann

In this section, Number To Character and Character to Number functions will be written.


Share This Snippet To :

NumToChar & CharToNum

Example Usage : Excel Sheet Calculation.

/** * Number to Character Util * @param { string } num * @returns { string } Character String */ export const numberToChar = (num: number): string => { const division = Math.floor(num / 26) const remainder = Math.floor(num % 26) const char = String.fromCharCode(remainder + 97).toUpperCase() return division - 1 >= 0 ? numberToChar(division - 1) + char : char } /** * Character to Number * @param { string } letters */ export const characterToNumber = (letters: string): void => { letters // Get each Letter on it own .split('') // Smaller First and then Bigger .reverse() // Convert them to base 26 numbers .map((letter, idx) => idx === 0 ? letter.toLowerCase().charCodeAt(0) - 97 : // The addition of 1 here is to oppose what we die for numberToChar letter.toLowerCase().charCodeAt(0) - 97 + 1 ) // Convert base 26 to base 10 .map((base26Number, position) => base26Number * 26 ** position) // Sum .reduce((sum: number, number: number) => sum + number, 0) }

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?