I have a program that needs to convert integers to binary and decimal. I have the binary portion working but am stuck on the decimal part. I'm trying to use intToFloat but not sure if that's right. Here is the code for the conversion functions.
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');
}
I need it to show the output of an integer being converted to a decimal and show the value as well, like it already does when it converts to binary.
parseInt(value, fromBase).toString(toBase)
To convert it to binary
parseInt(25,10).toString(2) //<== '25' is the value, 10 is the current base. 2 is the base you want to converted.
To convert it to decimal
parseInt(100011,2).toString(10)
To convert it to float
var num = 203
num.toFixed(6) // asnwer will be 203.000000
Related
I am trying to format a number as follows:
if no decimals in number then return 4 decimal (i.e. 100 would be 100.0000 and 0 would be 0.0000)
If there are decimals just return up to the last non 0 decimal(i.e. 100.000110000 would be 100.00011)
Below is my scrub function of which I load the value to be formatted into domtemp.value
The problem is in the "else if" below when checking for 0 decimals(or a whole number being entered). I never get there because the result always seems to be 0 whether or not I pass in 100 or 100.0011. Any ideas what I might be doing wrong with checking for a whole number?
function scrubAsFound() {
var i;
var length = 4;
for (i = 1; i <= length; i++) {
domtemp = document.querySelector('#equipment_asfound' + i);
// Check for empty values
if (isNaN(domtemp.value) || (!domtemp.value || 0 === domtemp.value.length))
{
domtemp.value = 0.0000;
domtemp.value = Number(domtemp.value).toFixed(4);
}
else if (Number(domtemp.value) % 1 != 0)
{
domtemp.value = Number(domtemp.value).toFixed(4);
}
else
{
domtemp.value = parseFloat(formatAsFound(domtemp.value));
}
}
}
function formatNumber(val) {
let numberVal = Number(val)
if (isNaN(numberVal)) {
numberVal = 0
}
const intVal = parseInt(numberVal)
return intVal + '.' + (numberVal + '').substr((intVal + '').length + 1).padEnd(4, '0')
}
console.log(formatNumber('abc') === '0.0000')
console.log(formatNumber('') === '0.0000')
console.log(formatNumber(0) === '0.0000')
console.log(formatNumber(2) === '2.0000')
console.log(formatNumber(2.1) === '2.1000')
console.log(formatNumber(2.00011) === '2.00011')
I need my code to only accept whole numbers, no decimals and should prompt an error when a decimal gets entered. I don't want a new function , I'm hoping I can just add lines to my function but I don't know what I need to add.
function number_function() {
number = parseInt(prompt('Enter a positive integer:'));
if (number < 0) {
alert('Error! Factorial for negative number does not exist. But I will show you the positive number');
number = number * -1;
let n = 1;
for (i = 1; i <= number; i++) {
n *= i;
}
alert("The factorial of " + number + " is " + n + ".");
} else if (number === 0) {
alert("Please enter a number greater than 0");
} else {
let n = 1;
for (i = 1; i <= number; i++) {
n *= i;
}
alert("The factorial of " + number + " is " + n + ".");
}
}
number_function();
You can do this to check if the number has decimals
const val = 10.7 % 1;
if (val !== 0) {
console.log('has decimals');
} else {
console.log('has no decimal');
}
JavaScript provides the built-in function Number.isInteger(n)
My calculator is rounding to 2 decimal places. How do I change it to 3 decimal places?
function formatDecimal(aFloat) {
var digits = "" + Math.round(100 * aFloat);
var length = digits.length;
if (length < 3) {
return "0." + digits;
}
else {
var dp = length - 2;
return digits.substring(0, dp) + "." + digits.substring(dp, length);
}
}
//Return the char of aString at index.
//If index is invalid, the results are undefined.
function charAt(aString, index) {
var length = aString.length;
return aString.substring(index, index + 1);
}
My goal is to create a program that checks whether the user input is a perfect number or not. It has validation for the numbers entered. If the input IS a perfect number, I'd like to print out each of the divisors. I tried using this method:
{
for(int number=2; number <= 10000 ; number++)
perfect(number);
return 0;
}
void perfect(int number)
{
int total = 0;
for (int i = 1; i < number; i++)
{
if (number % i == 0)
total += i;
}
if (number == total)
{
for (int x = 1; x < number; x++)
{
if (number % x == 0)
cout << x << " + ";
}
cout << " = " << number << endl;
}
}
However, I was unable to get the desired effect. I am very new to javascript and am struggling with inserting code in the correct way. Does anyone have a suggestion for how I can get the desired effect? Here is the code I have already written:
function check_prime() {
var input = document.getElementById("enteredNumber").value;
var number = parseInt(input);
if (isNaN(number)) {
alert("Oops! Please enter a valid number.");
document.getElementById("enteredNumber").value="";
document.getElementById("result").innerHTML = "";
document.getElementById("enteredNumber").focus();
}
else if (input.length === 0) {
alert("Please enter a number.");
document.getElementById("enteredNumber").focus();
}
else if (!isNaN(number)) {
if (is_perfect(number)) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number." ;
}
else {
document.getElementById("answer").innerHTML = "I'm sorry. " + number + " is not a perfect number. Try Again.";
}
}
else {
document.getElementById("answer").innerHTML = "Please enter a number.";
}
}
function is_perfect(number)
{
var temp = 0;
for(var i=1;i<=number/2;i++)
{
if(number%i === 0)
{
temp += i;
}
}
if(temp === number)
{
return true;
}
else
{
return false;
}
}
function clear_textbox(){
document.getElementById("answer").innerHTML = "";
document.getElementById("enteredNumber").value="";
document.getElementById("enteredNumber").focus();
}
I'd suggest revising your is_perfect() function to return an array of divisors if the number is perfect and null if the number is not perfect. Then the calling code has the divisors available for display when the input is a perfect number.
function is_perfect(number) {
var temp = 0;
var divisors = [];
for(var i=1;i<=number/2;i++) {
if (number%i === 0) {
divisors.push(i);
temp += i;
}
}
return temp === number ? divisors : null;
}
Then:
var divisors = is_perfect(number);
if (divisors) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number.";
// display the divisors somewhere; the alert is just for show
alert("Divisors: " + divisors.toString());
} else {
...
}
[Note: In an earlier version of this answer, I had initialized temp to 1 and divisors to [1] and had started the loop at 2, on the theory that 1 is always a divisor. Unfortunately, that's wrong, since 1 is not a proper divisor of 1. The revised version of is_perfect() now returns null for an argument of 1 instead of [1]. An alternative fix would have been to test explicitly for the case number === 1, but that's uglier (if perhaps a tiny bit more efficient, since it avoids one % evaluation).]
so I use 2^(n-1)*(2^n -1) formula (to generate a perfect number) and checking if last digit is 6 or 8 to check if x is perfect number.
Note: It's not perfect 100%
function pn(x) {
x = '' + x
for (var i = 0; i < Infinity; i++) {
perfnumgen = Math.pow(2, i - 1) * (Math.pow(2, i) - 1)
if (x === "" + perfnumgen && (perfnumgen % 10 === 8 || perfnumgen % 10 === 6))
return true
else if (perfnumgen > x)
return false
console.log("" + perfnumgen)
}
}
So I wrote a code that converts from decimal to hexadecimal and when i entered a 22 digit number or more the result is always 20 can someone explain why is this happening? here is the code, i went to online sites to convert such a number and it works there but why not with me?:
function convert(x) {
x = parseFloat(x);
var mod = 0;
var sum = "";
var FinalSum = "";
var y;
var str;
var slpha;
var beta;
while (x !== 0) {
mod = x % 16;
if (mod == 10) {
sum += "a";
} else if (mod == 11) {
sum += "b";
} else if (mod == 12) {
sum += "c";
} else if (mod == 13) {
sum += "d"
} else if (mod == 14) {
sum += "e";
} else if (mod == 15) {
sum += "f";
} else {
sum += mod;
}
x = parseInt(x / 16);
} //while loop end.
/* everything is right
till now but you have to
deal with the reverse issue */
str = sum;
alpha = sum.length - 1;
beta = alpha + 1;
while (alpha !== -1) {
FinalSum += str.slice(alpha, beta);
beta--;
alpha--;
} //while loop end.
console.log(FinalSum);
}
convert(1212312313123123123456);