簡體   English   中英

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

[英]How can I keep fraction formatting using JavaScript?

我的代碼專注於烹飪(香蕉面包食譜)。 根據人數的不同,有時我會制作兩種香蕉面包,而不是一種。 因此,我使用選擇工具通過更改每種成分的數量來解決這一問題。 但是,我的問題是JavaScript輸出小數而不是小數。 我想將數字保留為零。

理想
如果選擇1,則表示2杯面粉, 1/2茶匙鹽。
如果選擇2,則表示4杯面粉,1茶匙鹽。
如果選擇3,則表示6杯面粉, 1.5茶匙鹽。

實際發生的情況:
如果選擇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)); }; 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"> &frac12;</span> tsp salt into a large, dry bowl. </p> 

不用為選項1、2、3分配值a,b,c,而是使用后者的值:它更直觀。 您可以直接將該值用於乘法運算,而不必執行三個不同的if塊。 您也可以取消按鈕,因為您可以只響應選擇列表中的更改。

對於分數的特定顯示,我建議將所有邏輯放在一個類中,您可以將其稱為Rational 它將分子和分母分開,並允許對其進行乘法(和其他運算),並以所需的輸出格式顯示結果。 這樣,您可以將格式邏輯與配方邏輯隔離。

這是一個這樣的Rational類:可以很容易地擴展它以完成除乘法之外的其他工作(例如加法,除法,求反,求逆等):

 const gcd = (a, b) => b ? gcd(b, a % b) : a; class Rational { constructor(num, denom = 1) { if (num % 1 || denom % 1) throw "Rational constructor should get integer value(s)"; this.num = num * Math.sign(denom); this.denom = Math.abs(denom); } mul(b) { if (typeof b === "number") b = new Rational(b); const denom1 = gcd(this.denom, b.num); const denom2 = gcd(this.num, b.denom); return new Rational((this.num / denom2) * (b.num / denom1), (this.denom / denom1) * (b.denom / denom2)); } toString() { const sgn = this.num < 0 ? "-" : ""; const n = Math.abs(this.num); const i = Math.trunc(n / this.denom); const rem = (n % this.denom); const frac = rem ? rem + "/" + this.denom : ""; const remainder = { "1/2": "½", "1/3": "⅓", "2/3": "⅔", "1/4": "¼", "3/4": "¾", "1/5": "⅕", "2/5": "⅖", "3/5": "⅗", "4/5": "⅘", "1/6": "⅙", "5/6": "⅚", "1/7": "⅐", "1/8": "⅛", "3/8": "⅜", "5/8": "⅝", "7/8": "⅞", "1/9": "⅑", "1/10": "⅒" }[frac] || frac && ((i ? "+" : "") + frac); return sgn + (i || !remainder ? i : "") + remainder; } } document.getElementById("quantity").addEventListener("change", onSelectionChange); var n1 = new Rational(2); var n2 = new Rational(1, 2); function onSelectionChange() { var selection = +document.getElementById("quantity").value; document.getElementById('amount').textContent = n1.mul(selection); document.getElementById('amount2').textContent = n2.mul(selection); } 
 <label>How many Banana Bread's are you making?</label> <!-- Selection --> <select id="quantity"> <option>1</option> <option>2</option> <option>3</option> </select><br><br> <!-- HTML Recipe --> <p> Step 1: Add <span id="amount">2</span> cups flour and <span id="amount2">&frac12;</span> tsp salt into a large, dry bowl. </p> 

請注意,最后一個函數如何將精力集中在配方邏輯上,將分數的使用委托給Rational類,而后者又完全不了解配方業務。

對於較舊的JS引擎...

當您評論可能與不支持ES6語法的JS引擎相關的錯誤時,我在這里添加使用old-ES3語法的相同版本:

 function gcd (a, b) { return b ? gcd(b, a % b) : a; } function Rational(num, denom) { if (!denom) denom = 1; if (num % 1 || denom % 1) throw "Rational constructor should get integer value(s)"; this.num = num * Math.sign(denom); this.denom = Math.abs(denom); } Rational.prototype.mul = function (b) { if (typeof b === "number") b = new Rational(b); var denom1 = gcd(this.denom, b.num); var denom2 = gcd(this.num, b.denom); return new Rational((this.num / denom2) * (b.num / denom1), (this.denom / denom1) * (b.denom / denom2)); } Rational.prototype.toString = function () { var sgn = this.num < 0 ? "-" : ""; var n = Math.abs(this.num); var i = Math.floor(n / this.denom); var rem = (n % this.denom); var frac = rem ? rem + "/" + this.denom : ""; var remainder = { "1/2": "½", "1/3": "⅓", "2/3": "⅔", "1/4": "¼", "3/4": "¾", "1/5": "⅕", "2/5": "⅖", "3/5": "⅗", "4/5": "⅘", "1/6": "⅙", "5/6": "⅚", "1/7": "⅐", "1/8": "⅛", "3/8": "⅜", "5/8": "⅝", "7/8": "⅞", "1/9": "⅑", "1/10": "⅒" }[frac] || frac && ((i ? "+" : "") + frac); return sgn + (i || !remainder ? i : "") + remainder; } document.getElementById("quantity").addEventListener("change", onSelectionChange); var n1 = new Rational(2); var n2 = new Rational(1, 2); function onSelectionChange() { var selection = +document.getElementById("quantity").value; document.getElementById('amount').textContent = n1.mul(selection); document.getElementById('amount2').textContent = n2.mul(selection); } 
 <label>How many Banana Bread's are you making?</label> <!-- Selection --> <select id="quantity"> <option>1</option> <option>2</option> <option>3</option> </select><br><br> <!-- HTML Recipe --> <p> Step 1: Add <span id="amount">2</span> cups flour and <span id="amount2">&frac12;</span> tsp salt into a large, dry bowl. </p> 

...

    amount = Math.floor(numerator) + '/' + Math.floor(denominator);
    //EDIT
    switch (amount) {
        case '1/4':
            amount = '&frac14;';
        break;
        case '1/3':
            amount = '&‌#8531;';
        break;
        case '1/2':
            amount = '&frac12;';
        break;
        case '2/3':
            amount = '&‌#8532;';
        break;
        case '3/4':
            amount = '&frac34;';
        break;
        default:
            amount = amount;
        break;
    }
    //END OF EDIT
    if ( base ) {
        amount = base + ' ' + amount;
    }
    return amount;

要將0.5表示為分數,您使用的是html實體&frac12; 但是, numberToFraction()函數實際上返回的是“ 1/2”之類的字符串。

因此,您需要檢查金額是否為1/2,並用&frac12;替換&frac12; 並返回它。

此外,要更新跨度,您需要使用其.innerHTML屬性而不是.innerText-否則,您將看不到分數。

這是一個例子:

 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').innerHTML = numberToFraction(n2); } if (selection === 'b') { document.getElementById('amount').innerText = n1 * 2; document.getElementById('amount2').innerHTML = n2 * 2; } if (selection === 'c') { document.getElementById('amount').innerText = n1 * 3; document.getElementById('amount2').innerHTML = 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 (amount == "1/2") { amount = "&frac12;" } 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"> &frac12;</span> tsp salt into a large, dry bowl. </p> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM