Convert Numbers into fractions

Is there a way to convert numbers with decimals into fractions

How would you view the following:

  • Would 2 result in 2 or 2/1
  • Would 2.5 result in 2 1/2 or 5/2

I would like it to show the decimal side as a fraction for instance 2.25 to 2¼

image

Kept this screenshot for you, Jeff and @Darren_Murphy because I just remembered how you all taught me about how decimals don’t really look the same way they are. What is it called? Floating-point precision or something?

image

Anyway, the code was adjusted and it should work now. Please use this in your JavaScript column.

// Separate the integer part and the decimal part
const integerPart = Math.floor(p1);
const decimalPart = p1 - integerPart;

// If there is no decimal part, return the integer part
if (decimalPart === 0) {
    return `${integerPart}`;
}

// Convert decimal part to fraction
const gcd = (a, b) => b ? gcd(b, a % b) : a;
const decimalString = decimalPart.toFixed(10); // Fixing precision issues
const denominator = Math.pow(10, decimalString.split('.')[1].length);
const numerator = Math.round(decimalPart * denominator);
const commonDivisor = gcd(numerator, denominator);

const simplifiedNumerator = numerator / commonDivisor;
const simplifiedDenominator = denominator / commonDivisor;

// Return the mixed fraction
return `${integerPart} ${simplifiedNumerator}/${simplifiedDenominator}`;
4 Likes

It worked but I think there is something that need to be adjusted too. When the number with decimal has a zero like this 0.75 it’s having a zero too on the faction side too like this 0¾ instead of just the ¾. Is there a way ho adjust that sir

I have managed to adjust it. But thanks for sharing this sir.
// Separate the integer part and the decimal part
const integerPart = Math.floor(p1);
const decimalPart = p1 - integerPart;

// If there is no decimal part, return the integer part
if (decimalPart === 0) {
return ${integerPart} In stock;
}

// Convert decimal part to fraction
const gcd = (a, b) => b ? gcd(b, a % b) : a;
const decimalString = decimalPart.toFixed(10); // Fixing precision issues
const denominator = Math.pow(10, decimalString.split(‘.’)[1].length);
const numerator = Math.round(decimalPart * denominator);
const commonDivisor = gcd(numerator, denominator);

const simplifiedNumerator = numerator / commonDivisor;
const simplifiedDenominator = denominator / commonDivisor;

// If there is no integer part, return just the fraction part with “Kg In stock”
if (integerPart === 0) {
return ${simplifiedNumerator}/${simplifiedDenominator} Kg In stock;
}

// Return the mixed fraction with appropriate unit
return ${integerPart} ${simplifiedNumerator}/${simplifiedDenominator} Kg In stock;

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.