Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.
If you are converting price (in string) to decimal price then.... from decimal import Decimal price = "14000,45" price_in_decimal = Decimal(price. replace(',','. '))
The parseInt
function converts strings to numbers, and it takes a second argument specifying the base in which the string representation is:
var digit = parseInt(binary, 2);
See it in action.
ES6 supports binary numeric literals for integers, so if the binary string is immutable, as in the example code in the question, one could just type it in as it is with the prefix 0b
or 0B
:
var binary = 0b1101000; // code for 104
console.log(binary); // prints 104
Use the radix parameter of parseInt
:
var binary = "1101000";
var digit = parseInt(binary, 2);
console.log(digit);
parseInt()
with radix is a best solution (as was told by many):
But if you want to implement it without parseInt, here is an implementation:
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
var num = 10;
alert("Binary " + num.toString(2)); // 1010
alert("Octal " + num.toString(8)); // 12
alert("Hex " + num.toString(16)); // a
alert("Binary to Decimal " + parseInt("1010", 2)); // 10
alert("Octal to Decimal " + parseInt("12", 8)); // 10
alert("Hex to Decimal " + parseInt("a", 16)); // 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With