I'm trying to return 1/2
for all the input values that are <0.05
. (Don't bother with the math. I just want to return 1/2
for all the values that are <0.05
).
Here is the snippet that I'm working on:
function simpler(whole, x, y) {
if (x == 0) {
return whole;
} else if (x == 1 && y == 10) {
return whole + '<sup>' + 1 + '</sup>/<sub>' + 10 + '</sub>'
} else if (x == 2 && y == 10) {
return whole + '<sup>' + 1 + '</sup>/<sub>' + 5 + '</sub>'
} else if (x == 3 && y == 10) {
return whole + '<sup>' + 3 + '</sup>/<sub>' + 10 + '</sub>'
} else if (x == 4 && y == 10) {
return whole + '<sup>' + 2 + '</sup>/<sub>' + 5 + '</sub>'
} else if (x == 5 && y == 10) {
return whole + '<sup>' + 1 + '</sup>/<sub>' + 2 + '</sub>'
} else if (x == 6 && y == 10) {
return whole + '<sup>' + 3 + '</sup>/<sub>' + 5 + '</sub>'
} else if (x == 7 && y == 10) {
return whole + '<sup>' + 7 + '</sup>/<sub>' + 10 + '</sub>'
} else if (x == 8 && y == 10) {
return whole + '<sup>' + 4 + '</sup>/<sub>' + 5 + '</sub>'
} else if (x == 9 && y == 10) {
return whole + '<sup>' + 9 + '</sup>/<sub>' + 10 + '</sub>'
} else {
return whole + '<sup>' + x + '</sup>/<sub>' + y + '</sub>';
}
}
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 simpler(whole, this.numerator, this.denominator);
}
function f() {
var text = $('#text').val();
var roundUp = 0.4;
var digit = (text * 1).toFixed(1);
var frac = new Fraction()
frac.convert(digit, false)
$('#result').html(frac.toString());
}
$('#text').on('change', function() {
f();
});
f();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text" value="0.04" />
<div id="result"></div>
Here in the example, I've used toFixed(1)
to keep only one decimal of the input. As a result, if the input value is <0.05
it returns nothing. But I want to return 1/2
instead.