Binary to Decimal in Java Script [duplicate] - javascript

This question already has answers here:
How to convert binary string to decimal?
(10 answers)
Closed 9 years ago.
So I'm trying to convert binary to decimal in Javascript:
function binToDec(){
var binary = document.getElementById("binaryInput").value.split("").reverse();
var toDecimal = function(binary) {
return parseInt(binary,2);
}
}
But it's not working out for me... I'm new to JS so I'm not sure what's going on here.
Also, here is the "binaryInput" reference:
<td colspan="2"><input id="binaryInput" type="text" name="First Number" onfocus='onFocusInput(this);'></td>
Thanks for any help!

The problem is that you are splitting the input string. Look at the parseInt documentation:
If string [the value] is not a string, then it is converted to one.
However, converting the array (which is created because you split the string) back to a string results in '1,0,1,0,1,0,0,0', not '10101000'. '1,0,1,0,1,0,0,0' is not a valid binary number and parseInt therefore fails.
If you really want to reverse the input, you should use
document.getElementById("binaryInput").value.split("").reverse().join("");
which generates the correct string. If you don't want to reverse it, use
document.getElementById("binaryInput").value;

Your function should look like this:
function binToDec(){
//get the string from the input element
var binString = document.getElementById("binaryInput").value;
//remove any non binary character
binString = binString.replace(/[^01]+/g,'');
if(binString>''){
//if you want it to be reversed: binString = binString.split('').reverse().join('')
return parseInt(binString,2);
}
return 0;
}

Related

Javascript convert string value to Int value or Float [duplicate]

This question already has answers here:
How can I parse a string with a comma thousand separator to a number?
(17 answers)
Closed last month.
I want to convert string to Int or float type in JavaScript below is my code. or any solution is there in react library?
var a = '23,34.0';
console.log(parseFloat(a)); // 23
console.log(parseInt(a)) // 23
I want output like this:
`var a = '23,34.0';
output :
23,34.0 as a integer
I tried below codes
parseInt(a) parseFloat(a) Number(a)
this methods I tried but am not exact outputs.
Since your string is not a valid number, you cannot convert it.
You have to pass a valid number like 2324.5 to convert.
Trying this
var a = '2334.5'
console.log(parseFloat(a))
console.log(parseInt(a))
You will get 2334.5 and 2334 as output. "parseInt" will still yet cut of everything after the decimal point, because that's what an integer is, a whole number.

Javascript: String with hex to decimal [duplicate]

This question already has answers here:
Decoding hex-containing escape sequences in JavaScript strings
(6 answers)
Closed 2 years ago.
I've got this string containing multiple hexadecimal numbers:
let input = '\x01\x01\x02\x01';
I would like to see this transformed into: 1121 (the decimal representation of each hex number)
How would I go about this? I've tried numerous things, but the only output I get are some diamond shapes with a questionmark inside of it or syntax errors. Many thanks in advance!
Here is a simple method that escapes the string, removes empty elements, converts each number to is decimal digit, joins it as a string, and then converts the final result to a number.
function convert(string) {
string = escape(string);
string = string.split(/%/).filter(e=>e);
string = string.map(e => +("0x"+e));
return +string.join("");
}
// Test case
var decimal = convert('\x01\x01\x02\x01');
console.log(decimal);
To be able to work with the escape sequences itself and not the resulting whitespace, you habe to use String
raw then you can replace:
let input = String.raw`\x01\x01\x02\x01`;
console.log(
input
.replace(/\\x01/g, "1")
.replace(/\\x02/g, "2")
);

how to convert 1,800.00 to 1800 in javascript? [duplicate]

This question already has answers here:
How to convert a number with comma as string into float number in Javascript
(2 answers)
Closed 4 years ago.
I am trying to convert 1,100.00 or 1,800.00 to 1100 or 1800 by using Javascript Number() function but it gives NaN.
For Example:
var num = "1,100.00";
console.log(Number(num));
output: NaN
My requirement is If I have a number 1,800.00 it should convert to 1800 in Javascript.
Any help will be appreciated.
Thanks.
You can replace the , char using built-in replace function and then just convert to Number.
let number = "1,100.00";
console.log(Number(number.replace(',','')));
The Number() function converts the object argument to a number that represents the object's value. If the value cannot be converted to a legal number, NaN is returned.
You might have multiple , in the string replace all , from the string before passing to Number():
let numStr = '1,800.00';
let num = Number(numStr.replace(/,/g,''));
console.log(num);
.as-console-wrapper{
top: 0;
}
You can just replace the , with empty '' and then convert the string into number with + operator
let neu = "6,100.00";
document.write(+neu.replace(',',''));
You can try this.
var myValue = '1,800.00';
var myNumber = myValue.replace(/[^0-9.]/g, '');
var result = Math.abs(myNumber);
console.log( Math.floor(myNumber))
Here, in myValue, only number is taken removing other characters except dot.
Next thing is the value is converted to positive number using Math.abs method.
And at last using Math.floor function the fraction part is removed.

How to use isNAN and separator issues [duplicate]

This question already has answers here:
How to remove comma from number which comes dynamically in .tpl file
(7 answers)
How can I parse a string with a comma thousand separator to a number?
(17 answers)
Closed 5 years ago.
I need to find a way of either inputting separator eg, 12,000 without getting NaN message and if this can't be done then showing a message instead. I have looked through various sites and StackOverflow and can't work out how to do this (newbeeee issue). Current code as follows:
<script language="JavaScript" type="text/javascript">
function calcsavings()
{
var B1=document.forms[0].B1.value;
var B2n = Number("1516");
var B2=+B2n + +B1;
var B4 = Number("0.138");
var t;
for (i=0; i<document.forms[0].ITR.options.length; i++)
{
if (document.forms[0].ITR.options[i].selected)
t = document.forms[0].ITR.options[i].value;
}
var result=(B1/t-(B2/(1+B4)))*t
result=Math.round(result);
document.getElementById("childcaresavings").innerHTML=result;
}
</script>
I have stripped out the non-working code I tried before posting.
Is there anything wrong with adding a NaN check for result?
result=Math.round(result);
var htmlContent = Number.isNaN(result) ? "not a valid number" : result;
document.getElementById("childcaresavings").innerHTML=htmlContent ;
edit: If you're looking for a casual use of parsing. You can just use a global replace that will remove anything except numbers and periods.
if (document.forms[0].ITR.options[i].selected) {
var inputVal = document.forms[0].ITR.options[i].value;
var removedCommas = inputVal.replace(/[,]/g, "")
if (removedCommas[0] === "£") {
removedCommas = removedCommas.slice(1, removedCommas.length)
}
t = removedCommas
}
What this does: It takes your input and removes all commas and £ if it is the first character in the input. Assuming your user enters a sane entry, it will process the number as expected. If your use enters anything weird like / * & #, etc, NaN will be returned and your error will show.

How can I convert my string to a number in Javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to convert String variable to int in javascript?
I have the following:
var dataElapsed = $("#stats-list").attr("data-elapsed");
This creates a string called dataElapsed but I expect a number. How can I convert this?
Is there some way to convert with JQuery? or do I have to use some Javascript way?
Try this(assuming the data attributes have valid numeric values):
var dataElapsed = parseFloat($("#stats-list").attr("data-elapsed")); //for decimal.
or
var dataElapsed = parseInt($("#stats-list").attr("data-elapsed"), 10); //for integer.
You can use the .data() method to get values from data attributes
var dataElapsed = $("#stats-list").data("elapsed");

Categories

Resources