如何使用 JavaScript 保持分数格式?

我的代码专注于烹饪(香蕉面包食谱)。根据人数,我有时会做两个香蕉面包而不是一个。因此,我使用选择工具通过更改每种成分的数量来说明这一点。然而,我的问题是 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));

  };



慕尼黑的夜晚无繁华
浏览 203回答 3
3回答

手掌心

...&nbsp; &nbsp; amount = Math.floor(numerator) + '/' + Math.floor(denominator);&nbsp; &nbsp; //EDIT&nbsp; &nbsp; switch (amount) {&nbsp; &nbsp; &nbsp; &nbsp; case '1/4':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; amount = '&frac14;';&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case '1/3':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; amount = '&‌#8531;';&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case '1/2':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; amount = '&frac12;';&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case '2/3':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; amount = '&‌#8532;';&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case '3/4':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; amount = '&frac34;';&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; amount = amount;&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; //END OF EDIT&nbsp; &nbsp; if ( base ) {&nbsp; &nbsp; &nbsp; &nbsp; amount = base + ' ' + amount;&nbsp; &nbsp; }&nbsp; &nbsp; return amount;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript