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!
This code is great .I use it when I am working with fractions .It works perfectly .I wonder how it was made .
Thank you very much for your comment, Mathew!
Well, it’s all there in the code 😉
If you find this content useful, you can buy me a cup of coffee ;)
https://ko-fi.com/assemblysys