Javascript function equivalent to Delphi Frac

Asked

Viewed 68 times

-2

I need a function in Javascript that returns the fractional part of a floating point number.

Example:

if Frac( num1 / num2 ) > 0 then begin

2 answers

2


Looking for Delphi documentation found this function System.Frac().
Follows excerpt from the documentation:

function Frac(const X: Extended): Extended;

Description

Returns the fractional part of a real number.

In the Delphi code, the function Frac returns the fractional part of the argument X.

X is a real type expression. The result is the fractional part of X;
that is to say, Frac(X) = X - Int (X).

Then three things must be observed:

  • In javascript the numerical type Number is closest to the Delphi type System.Extended.
  • Function documentation shows how it works Frac(X) = X - Int (X).
  • The Delphi function System.Int() returns the integer part of a real number that is equivalent to javascript Math.trunc().

Then a possible alternative in javascript emulating the function Frac(X) delphi would be:

//Frac(X) = X - Int (X)

const num1 = 13;
const num2 = 3;

function frac(x) {
  return x - Math.trunc(x);
}


console.log(`Resultado de frac(num1/num2): ${frac(num1/num2)}`);
Observing:

The function has not been used parseInt() for the function converts its first argument to a string before returning the integer.

-3

From what I understand you need something like this:

var numberToFraction = function( amount ) {
    // This is a whole number and doesn't need modification.
    if ( parseFloat( amount ) === parseInt( amount ) ) {
        return amount;
    }
    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;
};

For testing:

numberToFraction(0.25);

will return: "1/4"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.