From Decimal to Binary system - javascript

I want to make an easy website because I want to learn javascript. The website will have just one (number) input named "number". After clicking on submit button the website will convert the number from decimal to binary system and show the answer.
This is the javascript part that should convert the number and show the answer in a div with ID = result:
var selectedNumber = document.getElementByName("number").value;
var k = [];
var a = 0;
var b = 1;
while (selectedNumber > 1){
if(selectedNumber%2 < 1){
k=k.append(a);
selectedNumber = Math.floor(selectedNumber/2);
}
else{
k=k.append(b);
selectedNumber = Math.floor(selectedNumber/2);
}
}
k=k.append(b);
for i in reversed(k){
document.getElementById("result").innerHETML = i;
}
Unfortunately, I don't have much experience using javascript and this code doesn't work. I've made a similar program in python and based this code on that in python.

Here's the corrected code:
Tip - Whenever you have to glue two numbers to form a string make sure to do 1 + "" +2
var selectedNumber = 105;//document.getElementByName("number").value;
var k = [];
var a = 0;
var b = 1;
var output = '';
while (selectedNumber > 1){
if(selectedNumber%2 < 1){
k=k+""+a;
selectedNumber = Math.floor(selectedNumber/2);
}
else{
k=k+""+b;
selectedNumber = Math.floor(selectedNumber/2);
}
}
k=k+""+b;
console.log(k);
//document.getElementByName("number").value = k;

Simplest way is to use toString(2) method.
let a =7
console.log(a.toString(2))
I have made some minor changes to your code. removed redundant lines. i am appending values to a front of string instead of an array ( which you later reverse and join).
function handle(){
let selectedNumber = document.getElementById("number").value;
let k = '',a = 0, b = 1;
while (selectedNumber > 1){
if(selectedNumber%2 < 1){
k= a+k
}
else{
k=b+k
}
selectedNumber = Math.floor(selectedNumber/2);
}
k=b+k;
document.getElementById("result").innerHTML = k;
}
#result{
color: green;
font-size:25px;
}
<input id='number' placeholder='enter value'></input>
<button onClick=handle()>Convert to binary</button>
<div id='result'></div>

It's a whole lot simpler than that. The .toString() method takes an optional argument that can be used to convert a number to a different numerical base system, like its binary, octal or hex values.
Prepending the input's value with +, forces the input's value to become a number.
document.querySelector("button").addEventListener("click", function(){
let number = +document.querySelector("input").value; // Convert input into a string
console.clear();
console.log("The decimal: " + number + " converted to a binary is: " + number.toString(2));
console.log("The decimal: " + number + " converted to an octal is: " + number.toString(8));
console.log("The decimal: " + number + " converted to a hex is: " + number.toString(16));
});
<input><button>Convert!</button>

For this goal, actually you can forget all your code and simple use Number.prototype.toString(). It takes an optional argument of the base you want to use for convert the number to string.
Example:
const convert = () =>
{
let number = document.getElementById("iNumber").value;
binNumber = Number.parseInt(number, 10).toString(2);
document.getElementById("dRes").innerHTML = binNumber;
};
<input id="iNumber" type="number">
<button id="btnToBinary" onclick="convert()">
Convert To Binary
</button>
<div id="dRes"></div>

Related

Javascript number format to decimal

I have a question about decimal numbers. I need to convert my numbers to decimal but I couldn't get what I exactly want.
What I want is:
I want to convert 130000 to 130,000 and 20911.56 to 20,911,56 (etc.)
First of all I searched in here and found some solutions to change my numbers :
function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){
var numbers = string.toString().match(/\d+/g).join([]);
numbers = numbers.padStart(decimals+1, "0");
var splitNumbers = numbers.split("").reverse();
var mask = '';
splitNumbers.forEach(function(d,i){
if (i == decimals) { mask = decimal + mask; }
if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }
mask = d + mask;
});
return pre + mask + pos;
}
var element = document.getElementById("format");
var money= number_format("130000",2,',','.');
element.innerHTML = money;
This code above gave me 20.911,56 but it didn't give me 130,000. Instead it is 1,300,00.What should I do? Can't I have them on the same time?
Just use Intl.NumberFormat as follows:
const formatter = new Intl.NumberFormat('en');
console.log(formatter.format(130000)); // 130,000
console.log(formatter.format(20911.56)); // 20,911.56

Evaluate a number to numbers in an array in JavaScript

I am making a random number generator to assign tasks. I want to give everyone a random number then generate the random number. I then want to list the people in order of how close they were.
I thought maybe to iterate through the array and find the absolute difference between the winningNumber and the numbers in the way. However, I'm not sure how to link the numbers back to the name in the list.
How can I evaluate these numbers?
Fiddle here.
HTML:
Random Number Assigner
<p>Have tasks to assign but no volunteers? Sign them up here</p>
<div id="input-area">
<input type="text" placeholder="Lucky person here" id="input">
<button id="button">Add Them!</button>
<br>
<br>
<button id="random">Generate Random Number</button>
</div>
<hr>
<div id="list-area">
<ul id="list"></ul>
</div>
CSS:
#input-area {
width: 100%;
border: 1px solid black;
}
JavaScript:
function randomNumber() {
return Math.round((Math.random()) * 100);
};
var randomNumberValue;
var winningNumber;
var myArray = [];
$(document).ready(function () {
console.log("The JavaScript has loaded");
$('#button').on('click', function () {
randomNumberValue = randomNumber();
var inputValue = $('#input').val();
if (inputValue === "") {
return;
};
$('#list').append("<ul>" + inputValue + ": " + randomNumberValue + " </ul>");
myArray.push(randomNumberValue);
$('#input').val("");
});
$('#random').on('click', function () {
myArray.sort();
winningNumber = randomNumber();
if (winningNumber === 0) {
winningNumber++;
};
console.log(myArray);
console.log("The winning number is: " + winningNumber);
for (var i = 0; i < myArray.length; i++) {
i - winningNumber;
};
console.log(myArray);
});
});
With some small adaptions:
function randomNumber() {
return Math.round((Math.random()) * 100);
};
var randomNumberValue;
var winningNumber;
var myArray = [];
$(document).ready(function () {
console.log("The JavaScript has loaded");
$('#button').on('click', function () {
var randomNumberValue = randomNumber();
var inputValue = $('#input').val();
if (inputValue === "") {
return;
};
// an item in a list is the <li> element
$('#list').append("<li>" + inputValue + ": " + randomNumberValue + " </li>");
// to simplify things I've used normal arrays for storage
// instead of a list of {key:value} pairs
// Advantage of {key:value} pairs here would be an easier check for multiple name entries
myArray.push([randomNumberValue,inputValue]);
$('#input').val("");
});
$('#random').on('click', function () {
// not needed in this simple algorithm
// You can use a binary search if the array is sorted which would make it faster
// but also much more complicated and isn't worth the hassle for small lists
//myArray.sort();
var winningNumber = randomNumber();
// get the first number for a start (numbering starts at zero)
var current = myArray[0][0];
// we need something to keep the position of the entry
var pos = 0;
console.log("The winning number is: " + winningNumber);
for (var i = 0; i < myArray.length; i++) {
// the actual number at position i in the array
var value = myArray[i][0];
/*
Compute two differences
a) between the drawn number and the actual number
b) between the drawn number and the last number that was
nearest to the last actual number
If the actual difference a is smaller than the last difference
it is better, hence we keep it. We have to know where it was to
be able to name the winner and keep the position to do so.
*/
if(Math.abs(winningNumber - value) < Math.abs(winningNumber - current)){
current = value;
pos = i;
}
// No "else" here because, well, we don't need to do anything, just go on
// until something is found.
};
console.log("The winner is: " + myArray[pos][1]);
console.log(myArray.join(" | "));
});
});
One caveat: you do not check for double entries. Both, the name and the random number can repeat and need to be checked, otherwise it may fail in curious ways.

Increment numbers at end of alphanumeric string in JavaScript

I have alphanumeric strings that will always end in a number, but which may have other numbers embedded early on.
I need to increment the numeric ending and return new ID numbers.
Example:
A48-DBD7-398
Which will be incremented in a loop:
A48-DBD7-398
A48-DBD7-399
A48-DBD7-400
How do I separate out the numeric tail from the rest of the string, and then save the two parts into different variables?
I found several other S.O. questions that split numbers out of a string, but they cannot handle mixed alphanumeric characters in the first part -- or else they split out ALL the numbers, regardless where they are. I need to get only the trailing digits.
Update
I found a case where my solution does not work:
ABC123-DE45-1
Duplicates as:
ABC2
ABC3
ABC4
JS Fiddle demo
If you are interested in a different approach you could do something like this:
$('button').click(function () {
var value = $('#in').val(); // get value
for (var i = 1; i <= 5; i++) {
value = value.replace(/(\d+)$/, function (match, n) {
return ++n; // parse to int and increment number
}); // replace using pattern
$('#result')[0].innerHTML += '<br>' + value;
}
});
My 2 cents: use regex to identify the pattern and increment the last part.
function incrementAlphanumeric(str) {
const numPart = str.match(/(0?[1-9])+$|0?([1-9]+?0+)$/)[0];
const strPart = str.slice(0, str.indexOf(numPart));
const isLastIndexNine = numPart.match(/9$/);
// If we have a leading zero (e.g. - 'L100A099')
// or there is no prefix - we should just increment the number
if (isLastIndexNine || strPart != null) {
return strPart + numPart.replace(/\d+$/, (n) => ++n );
}
// Increment the number and add the missing zero
else {
return strPart + '0' + numPart.replace(/\d+$/, (n) => ++n );
}
}
works with the following formats for example:
TEST01A06
TEST-100-A100
TEST0001B-101
TEST001A100
TEST001A91
TEST1101
TEST1010
1010
Demo Repl - https://repl.it/#EdoMagen/Increment-alphanumeric-string
Here is another solution, in case it helps
$('button').click(function() {
var ser = $('#in').val();
var arr = ser.split("-");
var num = parseInt(arr[arr.length - 1]);
arr.splice(-1, 1);
var str = arr.join ('-');
for (n = 1; n <= 5; n++) {
num++;
ser = str + '-' + num;
$('#result').html($('#result').html() + '<br>' + ser);
}
});
div{width:80%;margin-top:30px;background:wheat;}
<input id="in" type="text" value="ABC123-DE45-1" />
<button>Go</button>
<div id="result"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I figured it out, and am posting the question for future seekers.
JS Fiddle demo
HTML:
<input id="in" type="text" value="A48-DBD7-395" />
<button>Go</button>
<div id="result"></div>
js/jQ:
$('button').click(function(){
var ser = $('#in').val();
var num = parseInt(ser.match(/\d+$/));
var pos = ser.indexOf(num);
var str = ser.slice(0,pos);
for (n=1;n<=5;n++){
num++;
ser = str + num;
$('#result').html( $('#result').html() +'<br>'+ser);
}
});
const s = "A48-DBD7-398";
s.split('-').reduce((a,b)=>{
if(Number(b)){b = Number(b) + 1}
return a +'-'+ b;
})
> "A48-DBD7-399"

Adding values in javascript [duplicate]

This question already has answers here:
Plus Arithmetic Operation
(7 answers)
Closed 8 years ago.
I am trying to add up the 2 values (bold) that are inputed by the user but instead of adding then mathematically (100+1 = 101) it adds them like this (100+1 = 1001).
$('#inputcost').keyup(function(){
var price = $(this).val();
});
function checkboxcost() {
var sum = 0;
var gn, elem;
for (i=0; i<2; i++) {
gn = 'extra'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value); }
}
**var total = (price.value + sum.toFixed(2));
document.getElementById('totalcost').value = "$" + total;**
}
</script>
<input id="totalcost" disabled/>
The problem is, as you suspect, in this line:
var total = (price.value + sum.toFixed(2));
The problem is that .toFixed converts the number to a string for display. So you are trying to add a string to a number, which results in concatenation, not addition.
You want to add the numbers together, then display the sum:
var total = (price.value + sum).toFixed(2);
With that said, I'm not sure where price.value is coming from, so it's possible that's a string too. In which case, convert it with the unary plus + operator:
var total = (+price.value + sum).toFixed(2);
Its treating price.value as String so convert that string to number like:
var total = (Number(price.value) + sum.toFixed(2));
it seems string addition is taking place.
So try converting string numbers to integer using parseInt() like:
var x = parseInt("1")
var y = parseInt("2")
var z = x + y
Try parseInt(price.value) + ...
It's because the types of the operands are strings and the + operator for two strings does concatenation, not addition.
If you convert them to numbers then you'll get a number result:
"1" + "2" == "12"
parseFloat("1") + parseFloat("2") == 3

JQuery/JavaScript increment number

I am trying to increment a number by a given value each second and retain the formatting using JavaScript or JQuery
I am struggling to do it.
Say I have a number like so:
1412015
the number which this can be incremented by each second is variable it could be anything beween 0.1 and 2.
Is it possible, if the value which it has to be incremented by each second is 0.54 to incremenet the number and have the following output:
1,412,016
1,412,017
1,412,018
Thanks
Eef
I'm not quite sure I understand your incrementation case and what you want to show.
However, I decided to chime in on a solution to format a number.
I've got two versions of a number format routine, one which parses an array, and one which formats with a regular expression. I'll admit they aren't the easiest to read, but I had fun coming up with the approach.
I've tried to describe the lines with comments in case you're curious
Array parsing version:
function formatNum(num) {
//Convert a formatted number to a normal number and split off any
//decimal places if they exist
var parts = String( num ).replace(/[^\d.]-/g,'').split('.');
//turn the string into a character array and reverse
var arr = parts[0].split('').reverse();
//initialize the return value
var str = '';
//As long as the array still has data to process (arr.length is
//anything but 0)
//Use a for loop so that it keeps count of the characters for me
for( var i = 0; arr.length; i++ ) {
//every 4th character that isn't a minus sign add a comma before
//we add the character
if( i && i%3 == 0 && arr[0] != '-' ) {
str = ',' + str ;
}
//add the character to the result
str = arr.shift() + str ;
}
//return the final result appending the previously split decimal place
//if necessary
return str + ( parts[1] ? '.'+parts[1] : '' );
}
Regular Expression version:
function formatNum(num) {
//Turn a formatted number into a normal number and separate the
//decimal places
var parts = String( num ).replace(/[^\d.]-/g,'').split('.');
//reverse the string
var str = parts[0].split('').reverse().join('');
//initialize the return value
var retVal = '';
//This gets complicated. As long as the previous result of the regular
//expression replace is NOT the same as the current replacement,
//keep replacing and adding commas.
while( retVal != (str = str.replace(/(\d{3})(\d{1,3})/,'$1,$2')) ) {
retVal = str;
}
//If there were decimal points return them back with the reversed string
if( parts[1] ) {
return retVal.split('').reverse().join('') + '.' + parts[1];
}
//return the reversed string
return retVal.split('').reverse().join('');
}
Assuming you want to output a formatted number every second incremented by 0.54 you could use an interval to do your incrementation and outputting.
Super Short Firefox with Firebug only example:
var num = 1412015;
setInterval(function(){
//Your 0.54 value... why? I don't know... but I'll run with it.
num += 0.54;
console.log( formatNum( num ) );
},1000);
You can see it all in action here: http://jsbin.com/opoze
To increment a value on every second use this structure:
var number = 0; // put your initial value here
function incrementNumber () {
number += 1; // you can increment by anything you like here
}
// this will run incrementNumber() every second (interval is in ms)
setInterval(incrementNumber, 1000);
This will format numbers for you:
function formatNumber(num) {
num = String(num);
if (num.length <= 3) {
return num;
} else {
var last3nums = num.substring(num.length - 3, num.length);
var remindingPart = num.substring(0, num.length - 3);
return formatNumber(remindingPart) + ',' + last3nums;
}
}
function rounded_inc(x, n) {
return x + Math.ceil(n);
}
var x = 1412015;
x = rounded_inc(x, 0.54);

Categories

Resources