My code is focused on cooking (Banana Bread recipe). Depending on the number of people, I will sometimes make two Banana Bread's as opposed to one. Thus, I use the selection tool to account for this by changing the amount of each ingredient. Yet, my problem is JavaScript outputting decimals instead of fractions. I want to keep the numbers in fractions.
Ideal
If 1 was selected, it would say 2 cups flour, ½ tsp salt.
If 2 was selected, it would say 4 cups flour, 1 tsp salt.
If 3 was selected, it would say 6 cups flour, 1 ½ tsp salt.
What actually happens:
If 1 was selected, it would say 2 cups flour, 0.5 tsp salt.
If 2 was selected, it would say 4 cups flour, 1 tsp salt.
If 3 was selected, it would say 6 cups flour, 1.5 tsp salt.
Code:
document.getElementById("button").addEventListener("click", onButtonClick);
function onButtonClick() {
document.getElementById("amount").innerText = 2;
document.getElementById("amount2").innerText = 1 / 2;
var n1 = document.getElementById("amount").innerText;
var n2 = document.getElementById("amount2").innerText;
var selection = document.getElementById("quantity").value;
if (selection === 'a') {
document.getElementById('amount').innerText = n1;
document.getElementById('amount2').innerText = numberToFraction(n2);
}
if (selection === 'b') {
document.getElementById('amount').innerText = n1 * 2;
document.getElementById('amount2').innerText = n2 * 2;
}
if (selection === 'c') {
document.getElementById('amount').innerText = n1 * 3;
document.getElementById('amount2').innerText = numberToFraction(n2 * 3)
}
}
var numberToFraction = function(amount) {
// This is a whole number and doesn't need modification.
if (parseFloat(amount) === parseInt(amount)) {
return amount;
}
// Next 12 lines are cribbed from https://stackoverflow.com/a/23575406.
var gcd = function(a, b) {
if (b < 0.0000001) {
return a;
}
return gcd(b, Math.floor(a % b));
};
var len = amount.toString().length - 2;
var denominator = Math.pow(10, len);
var numerator = amount * denominator;
var divisor = gcd(numerator, denominator);
numerator /= divisor;
denominator /= divisor;
var base = 0;
// In a scenario like 3/2, convert to 1 1/2
// by pulling out the base number and reducing the numerator.
if (numerator > denominator) {
base = Math.floor(numerator / denominator);
numerator -= base * denominator;
}
amount = Math.floor(numerator) + '/' + Math.floor(denominator);
if (base) {
amount = base + ' ' + amount;
}
return amount;
};
<label> How many Banana Bread's are you making? </label>
<!-- Selection -->
<select id="quantity">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select><br><br>
<!-- Button -->
<button id="button" type="button">Let's get started!</button><br><br>
<!-- HTML Recipe -->
<p>
Step 1: Add
<span id="amount">2</span> cups flour and
<span id="amount2"> ½</span> tsp salt into a large, dry bowl.
</p>