Last active
August 29, 2015 14:14
-
-
Save yisibl/a6020ff67087a1cc1527 to your computer and use it in GitHub Desktop.
Number to fraction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//最大公约数 | |
function gcd(a, b) { | |
if (b === 0) return a | |
return gcd(b, a % b) | |
} | |
function num2fraction(num) { | |
if (num === 0) return 0 | |
if (typeof num === "string") { | |
num = parseFloat(num) | |
} | |
var number = num * 100000000 | |
//分子 | |
var numerator = number / gcd(number, 100000000) | |
//分母 | |
var denominator = 100000000 / gcd(number, 100000000) | |
//分数 | |
var fraction = numerator + '/' + denominator | |
return fraction | |
} | |
num2fraction.prototype = { | |
toString: function() { | |
return (this.denominator === 1) ? this.numerator.toString() : (this.numerator + '/' + this.denominator) | |
} | |
} | |
module.exports = num2fraction | |
console.log(num2fraction(0)) // => 0 | |
console.log(num2fraction(1.3)) // => 13/10 | |
console.log(num2fraction(1.4)) // => 7/5 | |
console.log(num2fraction(1.5)) // => 3/2 | |
console.log(num2fraction(2)) // => 2/1 | |
console.log(num2fraction(3)) // => 3/1 | |
console.log(num2fraction('1.5px')) // => 3/2 | |
console.log(num2fraction(3).toString()) // => 3/1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment