我正在使用JavaScript科学计算器上的按钮,通过此代码将小数转换为分数:
$('#button-frac').click(function(){
var factor;
// Finds the highest common factor of 2 numbers
function highestCommonFactor() {
for (factor = numerator; factor > 0; factor--) {
if ((numerator % factor == 0) && (denominator % factor == 0)) {
return factor;
}
}
}
// Enter a decimal to convert to a fraction
var decimal = this.form.display.value;
// Split the decimal
var decimalArray = decimal.split(".");
var leftDecimalPart = decimalArray[0];
var rightDecimalPart = decimalArray[1];
// Save decimal part only for later use
var decimalOnly = "0." + rightDecimalPart;
// Find the decimal multiplier
var multiplier = "1";
for (var i = 0; i < rightDecimalPart.length; i++) {
multiplier += "0";
}
// Create numerator by multiplying the multiplier and decimal part together
var numerator = Number(multiplier) * Number(decimalOnly);
var denominator = multiplier;
// Find the highest common factor for the numerator and denominator
highestCommonFactor();
// Simplify the fraction by dividing the numerator and denominator by the factor
var numerator = Number(numerator) / Number(factor);
var denominator = Number(denominator) / Number(factor);
// Output as a mixed number fraction (depending on input)
var mixedNumber = leftDecimalPart + " " + numerator + "/" + denominator;
// Output as a proper fraction or improper fraction (depending on input)
var numerator = numerator + (leftDecimalPart * denominator);
var fraction = numerator + "/" + denominator;
// Display solution in input #disp
$('#disp').val(fraction);
});
这很有效,但如果十进制是非终止并且重复脚本崩溃。知道如何解决这个问题吗?也许有一种方法可以检查十进制是否重复并确定重复的字符串的长度,然后取出该字符串并将其表示为具有相同位数的数字,全部为9?作为一个相对较新的JavaScript,我不知所措。
答案 0 :(得分:0)
使用此项并在最多20个重复的字符后围绕小数点。
Consumer<Integer>&Serializable
使用Supplier<String>&Serializable
它会:
Math.fraction=function(x){
return x?+x?x.toString().includes(".")?x.toString().replace(".","")/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length))+"/"+("1"+"0".repeat(x.toString().split(".")[1].length))/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length)):x+"/1":NaN:void 0;
}
(对包含分子和分母的数组使用Math.fraction(2.56)
)请注意,这会使用已弃用的string
,因此在某些浏览器中可能不兼容。
测试here