在这里,在下面的例子中,我使用toFixed(1)
只保留输入的一个小数。因此,无论输入是什么,我只获得值x.0, x.1, x.2, x.3, x.4,
... x.9
。结果分别是y 0/1, y 1/10, y 1/5, y 3/10, y 2/5,
... y 9/10
。此处x
和y
只是任意数字。
但我正试图让它更加简化,例如:
1.0 -> 1
1.1 -> 1 1/5
1.2 -> 1 1/5
1.3 -> 1 2/5
1.4 -> 1 2/5
1.5 -> 1 1/2
1.6 -> 1 3/5
1.7 -> 1 4/5
1.8 -> 1 4/5
1.9 -> 2
我在这里要做的是忽略像1/10, 3/10, 7/10, 9/10
这样的分数。
这是我正在处理的片段:
function Fraction() {}
Fraction.prototype.convert = function(x, improper) {
improper = improper || false;
var abs = Math.abs(x);
this.sign = x / abs;
x = abs;
var stack = 0;
this.whole = !improper ? Math.floor(x) : 0;
var fractional = !improper ? x - this.whole : abs;
function recurs(x) {
stack++;
var intgr = Math.floor(x);
var dec = (x - intgr);
if (dec < 0.0019 || stack > 20) return [intgr, 1];
var num = recurs(1 / dec);
return [intgr * num[0] + num[1], num[0]]
}
var t = recurs(fractional);
this.numerator = t[0];
this.denominator = t[1];
}
Fraction.prototype.toString = function() {
var l = this.sign.toString().length;
var sign = l === 2 ? '-' : '';
var whole = this.whole !== 0 ? this.sign * this.whole + ' ' : sign;
return whole + '<sup>' + this.numerator + '</sup>/<sub>' + this.denominator + '</sub>';
}
var text = $('#text').val();
var digit = (text * 1).toFixed(1);
var frac = new Fraction()
frac.convert(digit, false)
$('#result').html(frac.toString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text" value="1.3456" />
<div id="result"></div>