Javascript: String with hex to decimal [duplicate] - javascript

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")
);

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.

how to put a divider char between a number string in javascript for example I have 123456 and I want to be 123,456 or 1000000 to 1,000,000 [duplicate]

This question already has answers here:
How to format numbers? [duplicate]
(17 answers)
Closed 2 years ago.
I want to put a price on something and I get a string number and it should be divided by every 3 letters
but what eve I try to do I can't
is there any function or way that could be helpful ?
The simplest way is using Number#toLocaleString with a locale. The locale en-US uses commas to delimit every third digit and a dot to delimit the decimal fractional part.
const n = 1000000
const fractional = 12345.67
console.log(n.toLocaleString('en-US')) // 1,000,000
console.log(fractional.toLocaleString('en-US')) // 12,345.67
Use this function:
function numWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
console.log(numWithCommas(100000));

Write a JavaScript function that reverse a number [duplicate]

This question already has answers here:
JavaScript: How to reverse a number?
(19 answers)
Closed 3 years ago.
Result shows "n.split is not a function" unless i include n=n+" " the following code.What does third line mean?
function reverse_a_number(n)
{
n = n + "";
return n.split("").reverse().join("");
}
console.log(reverse_a_number(32243));
There is no split function in Number.prototype. So, n = n + "" is just a simple way to convert a number to a string.
From the spec
If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
If one of the operands in an expression with + is a string, the other operand is also coerced to a string and concatenated with it
console.log( 1 + 1 ) // sum
console.log( 1 + "1" ) // concatenation
console.log( true + "string" ) // concatenation
In javascript , there is no Explicit declaration of datatype, by assigning value to the variable , it implicitly takes the datatype like int,string.
In your case,Simple you are applying String function to integer , so you are getting Error.
So first convert integer value into String by using "toString()" function.
Solution:
function reverse_a_number(n) {
//Casting
n=n.toString();
return Number(n.split("").reverse().join(""));
}
console.log(reverse_a_number(32243));
There is no split function for Number. You can do this as an alternate
+String.prototype.split.call(32243,'').reverse().join('')
What the above code does?
I am using split method in String class via context switching for number which returns array.
Then we are reversing the number and joining it.
Then unary plus converts it to number.
As #briosheje mentioned, you can also use the following
+[...''+32243].reverse().join('')
Cast the number to a string and then use split as numerical values don't have the split function. Again cast it to a number while returning
function reverse_a_number(n) {
n=n.toString();
return Number(n.split("").reverse().join(""));
}
console.log(reverse_a_number(32243));
The reason is that split method works only on string values and your passing integer value as argument, that's why it's working only after casting it to string
You can't split a number. By using n = n + "", you're casting it a string and then splitting it. However, you're also returning a string! You'll want to cast it back to an integer before you return it.
Hmm.. I think this could be solved easily.
turn the number to a string, this lets you turn it to an array
Split it to a array
use array's function 'reversed'
join it
turn it to an number or int again.
const number = 3211232;
const numberReversed = parseInt(number.toString().split("").reverse().join(""));
console.log(numberReversed);

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.

Binary to Decimal in Java Script [duplicate]

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;
}

Categories

Resources