Convert a decimal number into a fraction

The title pretty much says it all: this JavaScript code takes a decimal number and converts it into a fraction.

This code:

  • recognizes 0.3333333 as 1/3
  • allows not to extract the integral part: 1.5 can return 1 1/2 (by default) or 3/2
  • works with negative numbers
/*
Description: Convert a decimal number into a fraction
Author: Michaël Niessen (© 2018)
Website: http://AssemblySys.com

If you find this script useful, you can show your
appreciation by getting Michaël a cup of coffee ;)
https://ko-fi.com/assemblysys

As long as this notice (including author name and details) is included and
UNALTERED, this code can be used and distributed freely.
*/

function decimalToFraction(value, donly = true) {
  var tolerance = 1.0E-6; // from how many decimals the number is rounded
  var h1 = 1;
  var h2 = 0;
  var k1 = 0;
  var k2 = 1;
  var negative = false;
  var i;

  if (parseInt(value) == value) { // if value is an integer, stop the script
    return value;
  } else if (value < 0) {
    negative = true;
    value = -value;
  }

  if (donly) {
    i = parseInt(value);
    value -= i;
  }

  var b = value;

  do {
    var a = Math.floor(b);
    console.log(a)
    var aux = h1;
    h1 = a * h1 + h2;
    h2 = aux;
    aux = k1;
    k1 = a * k1 + k2;
    k2 = aux;
    b = 1 / (b - a);
  } while (Math.abs(value - h1 / k1) > value * tolerance);

  return (negative ? "-" : '') + ((donly & (i != 0)) ? i + ' ' : '') + (h1 == 0 ? '' : h1 + "/" + k1);
}

A few examples:

decimalToFraction(0.666) returns 333/500
decimalToFraction(0.6666666) returns 2/3
decimalToFraction(-2.56) returns -2 14/25
decimalToFraction(2.5) returns 2 1/2
decimalToFraction(2.5, false) returns 5/2 (setting false ignores the integral part)

Please let me know in the comments below if there’s anything that can be improved, or simply if and where you use it. I’d very much appreciate to know who likes it!

If this helped you save time or solve a problem,
please buy me a coffee (or beer ;) ) to show your appreciation
and help support my work!

I'm available for hire!

If you need help with a website (HTML/CSS/JavaScript/PHP/MySQL), blog (15 years of experience with WordPress) or web app, get in touch and let's discuss what I can bring to your project, big or small.

2 thoughts on “Convert a decimal number into a fraction

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.