我有一个程序需要将整数转换为二进制和十进制。我有工作的二进制部分,但卡在小数部分。我正在尝试使用intToFloat
,但不确定是否正确。这是转换函数的代码。
if (cT[0].checked) {
// to binary
var dval = parseInt(val);
if (isNaN(dval)) {
alert("input value is not a number");
}
else if ((val % 1) !== 0 ) {
alert("number is not a integer");
}
else if (dval < 0) {
alert("Input value must be a positive integer");
}
else {
convertByArray(dval);
}
}
else if (cT[1].checked) {
//to decimal
var dval = parseFloat(val);
if (isNaN(dval)) {
alert("input value is not a number");
}
else if ((val % 1) !== 0 ) {
alert("number is not a integer");
}
else if (dval < 0) {
alert("Input value must be a positive integer");
}
else {
intToFloat(dval);
}
}
else {
alert("Please select a conversion type.");
}
}
function convertByArray(dval) {
var rA = new Array();
var r,i,j;
i=0;
while (dval > 0) {
r = dval % 2;
rA[i] = r;
var nV = (dval - r) / 2;
$("txtCalc").value = $("txtCalc").value + " Decimal " + dval + " divided by 2 = "
+ nV + " w/Remainder of: " + r + "\n";
i += 1;
dval = nV;
}
for(j=rA.length-1; j>= 0; j--) {
$("txtOut").value = $("txtOut").value + rA[j];
}
}
function intToFloat(num, decPlaces) {
return num + '.' + Array(decPlaces + 1).join('0');
}
我需要它来显示将整数转换为十进制的输出并显示值,就像将其转换为二进制时一样。
答案 0 :(得分:0)
parseInt(value, fromBase).toString(toBase)
将其转换为二进制
parseInt(25,10).toString(2) //<== '25' is the value, 10 is the current base. 2 is the base you want to converted.
将其转换为十进制
parseInt(100011,2).toString(10)
将其转换为浮点型
var num = 203
num.toFixed(6) // asnwer will be 203.000000