{"id":778,"date":"2011-11-26T21:53:23","date_gmt":"2011-11-27T03:53:23","guid":{"rendered":"http:\/\/bateru.com\/news\/?p=778"},"modified":"2011-11-26T21:58:59","modified_gmt":"2011-11-27T03:58:59","slug":"improved-code-for-javascript-decimal-to-fraction","status":"publish","type":"post","link":"https:\/\/bateru.com\/news\/2011\/11\/improved-code-for-javascript-decimal-to-fraction\/","title":{"rendered":"Improved Code for Javascript Decimal to Fraction"},"content":{"rendered":"<p>This post improves the code at &#8220;<a href=\"http:\/\/bateru.com\/news\/2011\/11\/code-of-the-day-javascript-decimal-to-fraction\/\">Code of the Day Javascript Decimal to fraction<\/a>&#8221; by using Euclid&#8217;s Algorithm to find the Great Common Factor or GCF, aka GCD. This method provides a speed up of 10x when compared to the original algorithm posted.<\/p>\n<p><b>Code<\/b><\/p>\n<pre lang='javascript'>\r\n\/**\r\n*@function gcd (aka Euclid's algorithm)\r\n*@purpose returns the greatest common factor between two numbers;\r\n*\/\r\nfunction gcd(a, b) {\r\n    return (b) ? gcd(b, a % b) : a;\r\n}\r\n\/**\r\n*@function dec2Frac\r\n*@purpose returns a decimal as a fraction.\r\n*\/\r\nvar dec2Frac = function ( num ) {\r\n\tvar top = num.toString().replace(\/\\d+[.]\/, '');\r\n\tvar bot = Math.pow(10, top.length);\r\n\tif (num > 1) {\r\n\t\ttop = +top + Math.floor(num) * bot;\r\n\t}\r\n\tvar x = gcd(top, bot);\r\n\treturn (top \/ x) + \"\/\" + (bot \/ x);\r\n};\r\n<\/pre>\n<p><b>Usage<\/b><\/p>\n<pre lang='javascript'>\r\ndec2Frac( 1.24325 ) \/\/ returns \"4973\/4000\"\r\ndec2Frac( 2.45 ) \/\/ returns \"49\/20\"\r\n<\/pre>\n<p><b>Speed Test between Version 1 and 2 of dec2Frac()<\/b><\/p>\n<pre lang='javascript'>\r\n\/\/@requires Firebug or Chrome Developer Tools\r\n\/\/The following code test the speed difference between the Version 1 and 2 of dec2Frac.\r\nfunction gcd(a, b) {\r\n    return (b) ? gcd(b, a % b) : a;\r\n}\r\nvar dec2FracV2 = function (d) {\r\n\tvar top = d.toString().replace(\/\\d+[.]\/, '');\r\n\tvar bot = Math.pow(10, top.length);\r\n\tif (d > 1) {\r\n\t\ttop = +top + Math.floor(d) * bot;\r\n\t}\r\n\tvar x = gcd(top, bot);\r\n\treturn (top \/ x) + \"\/\" + (bot \/ x);\r\n};\r\nfunction dec2FracV1(d) {\r\n    var df = 1, top = 1, bot = 1;\r\n    var limit = 1e5; \/\/Increase the limit to get more precision.\r\n \r\n    while (df != d && limit-- > 0) {\r\n        if (df < d) {\r\n            top += 1;\r\n        }\r\n        else {\r\n            bot += 1;\r\n            top = parseInt(d * bot, 10);\r\n        }\r\n        df = top \/ bot;\r\n    }\r\n    return top + '\/' + bot;\r\n}\r\nvar getRandomNum = function (i, decLen) {\r\n\treturn (Math.random() * (i || 1)).toFixed(decLen);\r\n};\r\n\r\nvar runTest = function ( funcName ) {\r\n\tvar func = { \"V1\": dec2FracV1, \"V2\": dec2FracV2 }[ funcName ];\r\n\tvar i = 1000;\r\n\twhile (i--) {\r\n\t\tnum = getRandomNum(10, 4);\r\n\t\tvar x = func(num);\r\n\t\tif (num != eval(x)) {\r\n\t\t\tconsole.warn(\"ERROR: Function %s, The fraction %s != %s\", funcName, num, x);\r\n\t\t}\r\n\t}\r\n};\r\nconsole.time( 'V1' );\r\nrunTest( \"V1\" );\r\nconsole.timeEnd( 'V1' );\r\n\r\nconsole.time( 'V2' );\r\nrunTest( \"V2\" );\r\nconsole.timeEnd( 'V2' );\r\n<\/pre>\n<p>Chrome Result:<br \/>\nV1: 11628ms<br \/>\nV2: 185ms<\/p>\n<p><b>Try the test out yourself<\/b><br \/>\n<a href=\"http:\/\/jsbin.com\/akobip\/2\">jsbin.com<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This post improves the code at &#8220;Code of the Day Javascript Decimal to fraction&#8221; by using Euclid&#8217;s Algorithm to find the Great Common Factor or GCF, aka GCD. This method provides a speed up of 10x when compared to the original algorithm posted. Code \/** *@function gcd (aka Euclid&#8217;s algorithm) *@purpose returns the greatest common &hellip; <a href=\"https:\/\/bateru.com\/news\/2011\/11\/improved-code-for-javascript-decimal-to-fraction\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Improved Code for Javascript Decimal to Fraction<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11,10],"tags":[30,164],"class_list":["post-778","post","type-post","status-publish","format-standard","hentry","category-frontend-tech","category-tutorials","tag-code-of-the-day","tag-javascript"],"_links":{"self":[{"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/posts\/778","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/comments?post=778"}],"version-history":[{"count":5,"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/posts\/778\/revisions"}],"predecessor-version":[{"id":781,"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/posts\/778\/revisions\/781"}],"wp:attachment":[{"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/media?parent=778"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/categories?post=778"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bateru.com\/news\/wp-json\/wp\/v2\/tags?post=778"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}