Created
January 9, 2017 13:52
-
-
Save cdevroe/dfa480270fdf283c8f8a4838d624cebb to your computer and use it in GitHub Desktop.
INCOMPLETE: Convert number into Roman numeral in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (win,doc) { | |
'use strict'; | |
var submit = document.getElementById('submit'); | |
submit.addEventListener( 'click', function(){ | |
var number = document.getElementById('number'), | |
roman_numeral = document.getElementById('roman'); | |
roman_numeral.innerHTML = convert_to_roman(number.value); | |
}, false); | |
function convert_to_roman(num) { | |
let roman = '', | |
i = 0, | |
thousands = 0, | |
hundreds = 0, | |
remainder = 0; | |
if ( num < 1 || num > 3999 ) return false; | |
if ( num > 1000 ) { | |
thousands = num / 1000; | |
for( i=1; i < Math.round(thousands); i++) { | |
roman += 'M'; | |
} | |
remainder = num % Math.round(thousands) * 1000; | |
} | |
if ( remainder > 0 ) { | |
if ( remainder > 500 ) { | |
hundreds = remainder / 500; | |
for( i=1; i < Math.floor(hundreds); i++) { | |
roman += 'D'; | |
} | |
remainder = remainder % Math.round(hundreds) * 500; | |
} | |
} | |
return roman; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment