JSFiddle - React, Tailwind, and code Playground
by henser
HTML
<body>
<div class="input-container">
<input id="inputVal" />
<p id="res">Please insert an integer or decimal number.</p>
</div>
</body>
CSS
html,
body{
width: 100%;
height: 100%;
background-color: #e3e3e3;
margin: 0;
padding: 0;
}
body{
display: table;
vertical-align: middle;
text-align: center;
}
.input-container{
display: table-cell;
width: 100%;
height: 100%;
vertical-align: middle;
text-align: center;
}
.input-container > input{
width: 180px;
height: 20px;
padding:0 10px;
border: 0;
background-color: rgba(120,120,120,.5);
}
.input-container > p{
color: #555;
margin-top: 30px;
font-family: 'Roboto', Helvetica, sans-serif;
}
JavaScript
// declare global variables
var inputEl = document.getElementById('inputVal'),
resEl = document.getElementById('res'),
coins = {0:[200, 0],1:[100, 0],2:[50, 0],3:[20, 0],4:[2, 0],5:[1, 0]},
curr = 0,
dotPos_val,
ifValid = true,
decimal = false;
// validate user input function
function validate(val){
var inputArr = inputEl.value == '' ? [0] : val.split(''),
dotPos = val.indexOf('.'),
dotLeft = val.substring(0,dotPos),
dotRight = val.substring(dotPos+1, dotPos.length),
rounded = Number('.'+dotRight).toFixed(2);
for(var j=0; inputArr.length > j; j++){
if((isNaN(inputArr[j]) && inputArr[j].indexOf('.') === -1) || (inputArr.length == 1 && inputArr[j] == 0)){
console.log('error: invalid input field value');
ifValid = false;
break;
}
}
// assume is int and set decimal value to false.
dotPos_val = val;
// check if input value is integer or decimal
// if decimal
if(dotPos != -1){
decimal = true;
// if there's no number after the comma add ".0"
if(dotRight.length === 0){
rounded = '.0';
}
// convert strings into numbers, calculate as integer total of pennies and put in global variable.
dotPos_val = Number(dotLeft)*100+Number(rounded.substring(2,4));
}
// call function to calculate minimum coins needed.
coinChange(dotPos_val);
}
// calculate minimum coins needed recursive function.
function coinChange(val){
var total = 0;
// in a first instance, if total pennies is >= 200
if(val >= coins[curr][0]){
// copy value minus 200 to new variable
total = val - coins[curr][0];
// increment one to associate array in the 200 key
coins[curr][1]++;
// call same function and check for 200 again.
coinChange(total);
// if total pennies is < 200
} else {
// copied variable equals tested variable
total = val;
// if copied variable is bigger...