Javascript理性 - 保留1的分母

时间:2015-11-20 19:19:49

标签: javascript rational-numbers

我需要在Javascript中使用有分母为1的有理数。所以,我有一些输入值,比如说1024,我需要将它存储为1024/1。当然1024 / 1只给我1024.那么我怎样才能获得原始的理性版本?

1 个答案:

答案 0 :(得分:0)

您对合理性有什么看法?如果只是简单算术,你可以自己编写。

下面是一个例子,你会为其他运营商做类似的事情。

希望这有帮助

function Rational(n, d) {
    this.n = n;
    this.d = d;
}
Rational.prototype.multiply = function(other) {
    return this.reduce(this.n * other.n, this.d * other.d)
}
Rational.prototype.reduce = function(n, d) {
    //http://stackoverflow.com/questions/4652468/is-there-a-javascript-function-that-reduces-a-fraction
    var gcd = function gcd(a,b){
        return b ? gcd(b, a%b) : a;
    };
    gcd = gcd(n,d);
    return new Rational(n/gcd, d/gcd);
}

var r1 = new Rational(1, 2);
var r2 = new Rational(24, 1);
var result = r1.multiply(r2);
console.log(result); // Rational(12, 1);
console.log(result.n + '/' + result.d); // 12/1