-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
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
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 argumentX
.
X
is a real type expression. The result is the fractional part ofX
;
that is to say,Frac(X) = X - Int (X)
.
Then three things must be observed:
System.Extended
.Frac(X) = X - Int (X)
.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)}`);
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 javascript delphi
You are not signed in. Login or sign up in order to post.