简体   繁体   中英

Convert a number to an alphabet letter

What I want is a function that takes in input a number and returns an alphabet letter (az).

This is my code (I get it from this question ):

 function numberToLetter(value) { const roundedPositiveValue = Math.round(Math.abs(value)) return (roundedPositiveValue + 9).toString(36) // return ((roundedPositiveValue % 26) + 9).toString(36) } function print(value) { document.write(`${value} → ${numberToLetter(value)}<br>`) } [-10, -2, 0, 2.5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 200].forEach(v => print(v))

It works but not in every case. For example it doesn't work for values > 26, so I tried using the modulo operator but in that case (commented line), it doesn't work for value 26. How can I fix it?

You could subtract one, to get a zero based value, apply modulo and add one to get values from one to 26.

 function numberToLetter(value) { const adjusted = ((Math.round(Math.abs(value)) - 1) % 26) + 1; return (adjusted + 9).toString(36); } function print(value) { document.write(`${value} → ${numberToLetter(value)}<br>`) } [-10, -2, 0, 2.5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 200].forEach(v => print(v))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM