Source: mivk from StackOverflow.com
Code
/**
@function dec2frac
@returns string
@purpose Convert a decimal to a fraction
*/
function dec2frac(d) {
var df = 1, top = 1, bot = 1;
var limit = 1e5; //Increase the limit to get more precision.
while (df != d && limit-- > 0) {
if (df < d) {
top += 1;
}
else {
bot += 1;
top = parseInt(d * bot, 10);
}
df = top / bot;
}
return top + '/' + bot;
}
Demo
JSBIN link
Example Output
dec2frac ( 0.1) returns "1/10"
dec2frac ( 0.2) returns "1/5"
dec2frac ( 0.5) returns "1/2"
dec2frac ( 0.9999) returns "9999/10000"
dec2frac ( 0.75) returns "3/4"
dec2frac ( 2.718281828459045) returns "135915/50000", but this evaluates to 2.7183
dec2frac ( 3.141592653589793) returns "157079/50000", but this evaluates to 3.14158
What REALLY is Data Science? Told by a Data Scientist - By Joma Tech
Writing perfect code is a challenging process. That's where code reviews come in to help…
"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"
"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"
My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…
View Comments
Improved code for this post.
http://bateru.com/news/2011/11/improved-code-for-javascript-decimal-to-fraction/