简体   繁体   中英

Cup to Fraction using JavaScript/jQuery

1 cup is assumed to be equal to 2.36 dl. I want a function that can input a decimal representing the cup/cups in dl and output the number of cup/cups as a fraction.

This is what I got this far:

  var dl = 2.36;

  cupToFraction(.78);  // 1/3 cup
  cupToFraction(2.36); // 1 cup      
  cupToFraction(4.72); // 2 cups
  cupToFraction(8.26); // 3 1/2 cups

  function cupToFraction (cup) {
    var deci = (cup / dl);
    alert(deci);
  }

One option is to use continued fractions to obtain a rational approximation:

var dl = 2.36;
function cupToFraction (cup) {
    var deci = (cup / dl);
    var integerPart = Math.floor(deci);
    deci -= integerPart;
    deci = 1 / deci;
    var c = [];
    // Tune these parameters for how far you want the continued fraction to go
    // 3 means at most 3 terms; 10 means no terms higher than 10.
    for (let i = 0; i < 3 && deci < 10; ++i) {
      let f = Math.floor(deci);
      c.push(f);
      deci -= f;
      deci = 1/deci;
    }
    if (c.length === 0) return [integerPart, 0, 1];
    var p = 1, q = c.pop();
    while (c.length > 0) {
      var int = c.pop();
      p = q*int + p;
      [p, q] = [q, p];
    }
    // Handle case like cupToFraction(2.35)
    if (p === q) { p = 0; integerPart++; }
    return [integerPart, p, q];
}

It returns an array whose elements are integerPart, numerator, denominator . For example, cupToFraction(8.26) gives [3, 1, 2] for 3 1/2 . I'm sure this algorithm could be more optimized, but this will have to do for now.

A maybe more robust and much simpler solution uses Fraction.js :

function cupToFraction(cup) {
  return new Fraction(cup).div(2.36).simplify(0.1).toFraction(true);
}

cupToFraction(.78); // "1/3"
cupToFraction(2.36); // "1"
cupToFraction(4.72); // "2"
cupToFraction(8.26); // "3 1/2"

Everything as you desire, but input numbers are translated to fractions using Farey sequences (very stable) and you can pass fractions alike:

cupToFraction("3 2/12"); // "1 1/3"

The accuracy can be controlled with the parameter of simplify(eps) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM