我的代码专注于烹饪(香蕉面包食谱)。根据人数,我有时会做两个香蕉面包而不是一个。因此,我使用选择工具通过更改每种成分的数量来说明这一点。然而,我的问题是 JavaScript 输出小数而不是分数。我想将数字保留在分数中。理想如果选择 1,它会说 2 杯面粉,½茶匙盐。如果选择 2,它会说 4 杯面粉,1 茶匙盐。如果选择 3,它会说 6 杯面粉,1 ½茶匙盐。实际发生的情况:如果选择 1,它会说 2 杯面粉,0.5 茶匙盐。如果选择 2,它会说 4 杯面粉,1 茶匙盐。如果选择 3,它会说 6 杯面粉,1.5 茶匙盐。代码: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)); };
3 回答
手掌心
TA贡献1942条经验 获得超3个赞
...
amount = Math.floor(numerator) + '/' + Math.floor(denominator);
//EDIT
switch (amount) {
case '1/4':
amount = '¼';
break;
case '1/3':
amount = '⅓';
break;
case '1/2':
amount = '½';
break;
case '2/3':
amount = '⅔';
break;
case '3/4':
amount = '¾';
break;
default:
amount = amount;
break;
}
//END OF EDIT
if ( base ) {
amount = base + ' ' + amount;
}
return amount;
添加回答
举报
0/150
提交
取消