convert decimal number to fraction in javascript or closest fraction

后端 未结 10 1573
温柔的废话
温柔的废话 2020-12-05 16:12

So i want to be able to convert any decimal number into fraction. In both forms such as one without remainder like this: 3/5 or with remainder: 3 1/4

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 16:39

    You can use brute force test on different denominators and retain the result that has least error.

    The algorithm below is an example of how you might go about this, but, suffers from being inefficient and limited to searching for denominators up to 10000.

    function find_rational( value, maxdenom ) {
      console.clear();
      console.log( "Looking up: " + value );
      let best = { numerator: 1, denominator: 1, error: Math.abs(value - 1) }
      if ( !maxdenom ) maxdenom = 10000;
      for ( let denominator = 1; best.error > 0 && denominator <= maxdenom; denominator++ ) {
        let numerator = Math.round( value * denominator );
        let error = Math.abs( value - numerator / denominator );
        if ( error >= best.error ) continue;
        best.numerator = numerator;
        best.denominator = denominator;
        best.error = error;
        console.log( "Intermediate result: "
                       + best.numerator + "/" + best.denominator
                       + " (" + ( best.numerator/best.denominator)
                       + " error " + best.error + " )" );
      }
      console.log( "Final result: " + JSON.stringify( best ) );
      return best;
    }
      
    function calc() {
        const value = parseFloat( $("#myInput").val() );
        if ( isNaN(value) ) {
            $( "#myResult" ).val( "NaN" );
            return;
        }
        const rational = find_rational( value, 10000 );
        $("#myResult").val( rational.numerator
                            + " / " + rational.denominator
                            + " ( Error: " + rational.error + " )" );
    }
    
    calc();
    
    
    

    Enter a decimal number:

    Resulting Rational:

    The above determines the .3435 as a fraction is 687 / 2000.

    Also, had you gave it PI (e.g. 3.1415926) it produces good looking fractions like 22/7 and 355/113.

提交回复
热议问题