本文介绍了jQuery将十进制结果转换为分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有将像素转换为英寸的代码.但是结果是十进制.
I have code that converts pixels into inches. But the result is a decimal.
如何让结果返回英寸的分数,例如:1/4而不是.25
How can I have the result return a fraction for the inch, example: 1/4 instead of .25
这是HTML:
<label>Pixels</label>
<input class="calcd" id="calc3" type="text" />
<input class="calcd" id="calc4" type="hidden" value="96" />
<br />Inches <span id="result2"></span>
这是Jquery:
$(document).ready(function(){
$(".calcd").keyup(function(){
var val1 = parseInt($("#calc3").val());
var val2 = parseInt($("#calc4").val());
if ( ! isNaN(val1) && ! isNaN(val2))
{
$("#result2").text((val1 / val2).toFixed(2));
}
});
});
我在stackoverflow上看到了这:
I see this here on stackoverflow:
在使用var decimal = eval(fraction);
的地方可以使用,但是对此感到困惑.
where using the var decimal = eval(fraction);
will work, but am confused on it.
这是 JsFiddle
推荐答案
有2个选项:
- 正在运行的演示=> : http://jsfiddle.net/Nn2yq/-将十进制数转换为分数/有理数
- 您可以使用以下代码: https://github.com/ekg/fraction.js
- Working demo =>: http://jsfiddle.net/Nn2yq/ -- Convert a decimal number to a fraction / rational number
- you can use this: https://github.com/ekg/fraction.js
此外,您只需要一个$(document).ready(function () {
希望这会有所帮助. :)
hope this helps. :)
编码
$(document).ready(function () {
$(".calc").keyup(function () {
var val1 = parseInt($("#calc1").val());
var val2 = parseInt($("#calc2").val());
if (!isNaN(val1) && !isNaN(val2)) {
$("#result").text(val1 * val2);
}
});
$(".calcd").keyup(function () {
var val1 = parseInt($("#calc3").val());
var val2 = parseInt($("#calc4").val());
if (!isNaN(val1) && !isNaN(val2)) {
$("#result2").text(fraction((val1 / val2).toFixed(2)));
}
});
});
//convert a decimal into a fraction
function fraction(decimal) {
if (!decimal) {
decimal = this;
}
whole = String(decimal).split('.')[0];
decimal = parseFloat("." + String(decimal).split('.')[1]);
num = "1";
for (z = 0; z < String(decimal).length - 2; z++) {
num += "0";
}
decimal = decimal * num;
num = parseInt(num);
for (z = 2; z < decimal + 1; z++) {
if (decimal % z == 0 && num % z == 0) {
decimal = decimal / z;
num = num / z;
z = 2;
}
}
//if format of fraction is xx/xxx
if (decimal.toString().length == 2 && num.toString().length == 3) {
//reduce by removing trailing 0's
decimal = Math.round(Math.round(decimal) / 10);
num = Math.round(Math.round(num) / 10);
}
//if format of fraction is xx/xx
else if (decimal.toString().length == 2 && num.toString().length == 2) {
decimal = Math.round(decimal / 10);
num = Math.round(num / 10);
}
//get highest common factor to simplify
var t = HCF(decimal, num);
//return the fraction after simplifying it
return ((whole == 0) ? "" : whole + " ") + decimal / t + "/" + num / t;
}
function HCF(u, v) {
var U = u,
V = v
while (true) {
if (!(U %= V)) return V
if (!(V %= U)) return U
}
}
工作屏幕截图
这篇关于jQuery将十进制结果转换为分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!