Skip to content

Instantly share code, notes, and snippets.

@yisibl yisibl/num2fraction.js

Last active Aug 29, 2015
Embed
What would you like to do?
Number to fraction
//最大公约数
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
You can’t perform that action at this time.