String Conversion in Javascript (Decimal to Binary) - javascript

A newbie here! Wondering why the following conversion fails!
var num = prompt("Enter num");
alert(num.toString(2));
If num input is 32. I get 32 as num alert message too.

try
(+num).toString(2)
,
Number(num).toString(2)
or
parseInt(num, 10).toString(2)
Any of those should work better for you.
The issue is that the toString method of javascript Number objects overrides the toString method of Object objects to accept an optional radix as an argument to provide the functionality you are looking for. The String object does not override Object's toString method, so any arguments passed in are ignored.
For more detailed information about these objects, see the docs at Mozilla:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String#Methods
or W3 schools:
http://www.w3schools.com/jsref/jsref_tostring_number.asp
http://www.w3schools.com/jsref/jsref_obj_string.asp

With this function you can specify length of the output.
For example decbin(7,4) produces 0111.
function decbin(dec,length){
var out = "";
while(length--)
out += (dec >> length ) & 1;
return out;
}
demo

Here is my solution that does not use parseInt, but rather a method that shows the logic behind the conversion of decimal to binary.
This method prints the bits to the array which you may later print out if you wish:
var number = 156;
var converted = [];
while(number>=1) {
converted.unshift(number%2);
number = Math.floor(number/2);
}
The converted array will now appear like so:
[1,0,0,1,1,1,0,0]
which of course converts back to 156.

/**
Convert a decimal number to binary
**/
var toBinary = function(decNum){
return parseInt(decNum,10).toString(2);
}
/**
Convert a binary number to decimal
**/
var toDecimal = function(binary) {
return parseInt(binary,2).toString(10);
}
Finally use it
var num= prompt("Enter num");
alert(toBinary(num));

Cast it to an integer first. At the moment you're converting a string to it's binary representation.
num = +num;

Related

How to print an n-bit number with a custom n-length character set in JavaScript without using toString

In the same way we have the hex "number" using the characters 123456789abcdef, and you can simply do integer.toString(16) to go from integer to hex:
> (16).toString(16)
'10'
... I would like to instead use a custom character set, and a custom base. So for hex say I wanted to use the characters 13579acegikmoqsu, then it would be something like this:
> (16).toString(16, '13579acegikmoqsu')
'ik'
I don't actually know what the output value would be in this case, just made that up. But I am looking for how to do this in JavaScript.
Another example outside of hex would be a, for example, base 6 number converted to a string using the character set and123, so it would be something like this:
> (16).toString(6, 'and123')
'a3d'
I don't know what the value is in this case here either, I don't know how to calculate it. Basically wondering how to do this in JavaScript, not necessarily using this toString api, preferably it would be a bit more low-level so I could also understand the logic behind it.
Likewise, it would be helpful to know how to reverse it, so to go from a3d => 16 as in this pseudo-example.
You could map the character values of the integer value as index
function toString(n, characters) {
var radix = characters.length;
return Array
.from(n.toString(radix), v => characters[parseInt(v, radix)])
.join('');
}
console.log(toString(16, '13579acegikmoqsu')); // 31
A version without toString and parseInt.
function toString(n, characters) {
var radix = characters.length,
temp = [];
do {
temp.unshift(n % radix);
n = Math.floor(n / radix);
} while (n)
return temp
.map(i => characters[i])
.join('');
}
console.log(toString(16, '13579acegikmoqsu')); // 31

Javascript - Format number to always show the original decimal places

I need a js function that show the original count of decimals in a number. For example:
value display
2.31 2
1.0 1
2.3500 4
The problem is that i dont know how get the count of decimals.
I have that code:
value=2.3500;
return CountofDecimals(value); // must be display 4:
Anything help??? Thanks :P
That's not possible. There's no difference between the number 3.5 and 3.50 in JavaScript, or indeed in any other common programming language.
If you actually mean they're strings (value = '2.3500' rather than value = 2.3500) then you can use indexOf:
var decimalPlaces = value.length - value.indexOf('.') - 1;
Caveat: I hate this answer, I don't really advocate it
Don't store it as a number, store it as a string. This can result in "stringly typed" code quickly so it is inadvisable. It is a workaround since JavaScript uses a float as the number type.
Alternatively store it as an Object and parse out the format via a function call:
{ value = "1.2345", decimal = 4}
and use that to create the correct number format. If I had the requirement this is probably the hack I'd use. Or, I would have my server return the formatted string as you can pull that off easily server side.
If it would be possible take these numbers as strings, it definitely is possible..And quite simple actually.
function countDecimals(string){
var delimiters = [",","."];
for(var i = 0; i<delimiters.length; i++){
if(string.indexOf(delimiters[i])==-1) continue;
else{
return string.substring(string.indexOf(delimiters[i])+1).length;
}
}
}
You could use this function:
function decimalplaces(number)
{
numberastring = number.toString(10);
decimalpoint = numberastring.indexOf(".");
if(decimalpoint == -1)
{
return 0;
}
else
{
return numberastring.length - decimalpoint - 1;
}
}

Summing variables with parseInt(); Not Working

What is the proper way to add the sum of multiple variables in Javascript?
This is what I'm trying to do. I've tried it with and without the quotes around my variables. I'm not getting a NaN or an Undefined or anything. No output whatsoever.
function setstat(){
document.getElementById('date').value = window.opener.document.getElementById('thisday').value;
document.getElementById('name').value = window.opener.document.getElementById('element_7').value;
document.getElementById('time').value = window.opener.document.getElementById('stwa').value;
inbcalls = window.opener.document.getElementById('element_6').value;
document.getElementById('totinb').value = inbcalls;
inbcallsp = parseInt("inbcalls",10);
asaptotal = window.opener.document.getElementById('asapcalls').value;
document.getElementById('asaptot').value = asaptotal;
asaptotalp = parseInt("asaptotal",10);
faxtotal = window.opener.document.getElementById('faxcalls').value;
document.getElementById('faxtot').value = faxtotal;
faxtotalp = parseInt("faxtotal",10);
obtotal = window.opener.document.getElementById('obcalls').value;
document.getElementById('obtot').value = obtotal;
totalcalls = inboundcallsp + asaptotalp + faxtotalp + obtotalp;
document.getElementById('totsum').value = totalcalls;
}
Why are you quoting the variable names?
inbcallsp = parseInt("inbcalls",10);
should be:
inbcallsp = parseInt(inbcalls, 10);
And the same for the rest of them. You want to parse the value of the variables, not the names of the variables; those will always result in NaN.
asaptotalp = parseInt("asaptotal",10);
"asaptotal" is recognize as the string not the variable
you should not quote it
When using parseInt always specify the radix as 10.
The function singnature: parseInt(string, radix)
The radix is optional but if ommited, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)
Example:
parseIn("05") ==== 0 -> true
parseIn("05", 10) ==== 5 -> true
Don't use ParseInt, sometimes it will not return the proper value.
Better use Number, for example:
var i=Number(your value)

JavaScript displaying a float to 2 decimal places

I wanted to display a number to 2 decimal places.
I thought I could use toPrecision(2) in JavaScript .
However, if the number is 0.05, I get 0.0500. I'd rather it stay the same.
See it on JSbin.
What is the best way to do this?
I can think of coding a few solutions, but I'd imagine (I hope) something like this is built in?
float_num.toFixed(2);
Note:toFixed() will round or pad with zeros if necessary to meet the specified length.
You could do it with the toFixed function, but it's buggy in IE. If you want a reliable solution, look at my answer here.
number.parseFloat(2) works but it returns a string.
If you'd like to preserve it as a number type you can use:
Math.round(number * 100) / 100
Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:
var num = response_from_a_function_or_something();
var fixedNum = parseFloat(num).toFixed( 2 );
with toFixed you can set length of decimal points like this:
let number = 6.1234
number.toFixed(2) // '6.12'
but toFixed returns a string and also if number doesn't have decimal point at all it will add redundant zeros.
let number = 6
number.toFixed(2) // '6.00'
to avoid this you have to convert the result to a number. you can do this with these two methods:
let number1 = 6
let number2 = 6.1234
// method 1
parseFloat(number1.toFixed(2)) // 6
parseFloat(number2.toFixed(2)) // 6.12
// method 2
+number1.toFixed(2) // 6
+number2.toFixed(2) // 6.12
Try toFixed instead of toPrecision.
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // return 1.01
round(1.004, 2); // return 1 instead of 1.00
The answer is following this link: http://www.jacklmoore.com/notes/rounding-in-javascript/
I used this way if you need 2 digits and not string type.
const exFloat = 3.14159265359;
console.log(parseFloat(exFloat.toFixed(2)));
You could try mixing Number() and toFixed().
Have your target number converted to a nice string with X digits then convert the formated string to a number.
Number( (myVar).toFixed(2) )
See example below:
var myNumber = 5.01;
var multiplier = 5;
$('#actionButton').on('click', function() {
$('#message').text( myNumber * multiplier );
});
$('#actionButton2').on('click', function() {
$('#message').text( Number( (myNumber * multiplier).toFixed(2) ) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button id="actionButton">Weird numbers</button>
<button id="actionButton2">Nice numbers</button>
<div id="message"></div>
The toFixed() method formats a number using fixed-point notation.
and here is the syntax
numObj.toFixed([digits])
digits argument is optional and by default is 0. And the return type is string not number. But you can convert it to number using
numObj.toFixed([digits]) * 1
It also can throws exceptions like TypeError, RangeError
Here is the full detail and compatibility in the browser.
let a = 0.0500
a.toFixed(2);
//output
0.05
There's also the Intl API to format decimals according to your locale value. This is important specially if the decimal separator isn't a dot "." but a comma "," instead, like it is the case in Germany.
Intl.NumberFormat('de-DE').formatToParts(0.05).reduce((acc, {value}) => acc += value, '');
Note that this will round to a maximum of 3 decimal places, just like the round() function suggested above in the default case. If you want to customize that behavior to specify the number of decimal places, there're options for minimum and maximum fraction digits:
Intl.NumberFormat('de-DE', {minimumFractionDigits: 3}).formatToParts(0.05)
float_num = parseFloat(float_num.toFixed(2))
I have made this function. It works fine but returns string.
function show_float_val(val,upto = 2){
var val = parseFloat(val);
return val.toFixed(upto);
}

Is there "0b" or something similar to represent a binary number in Javascript

I know that 0x is a prefix for hexadecimal numbers in Javascript. For example, 0xFF stands for the number 255.
Is there something similar for binary numbers ? I would expect 0b1111 to represent the number 15, but this doesn't work for me.
Update:
Newer versions of JavaScript -- specifically ECMAScript 6 -- have added support for binary (prefix 0b), octal (prefix 0o) and hexadecimal (prefix: 0x) numeric literals:
var bin = 0b1111; // bin will be set to 15
var oct = 0o17; // oct will be set to 15
var oxx = 017; // oxx will be set to 15
var hex = 0xF; // hex will be set to 15
// note: bB oO xX are all valid
This feature is already available in Firefox and Chrome. It's not currently supported in IE, but apparently will be when Spartan arrives.
(Thanks to Semicolon's comment and urish's answer for pointing this out.)
Original Answer:
No, there isn't an equivalent for binary numbers. JavaScript only supports numeric literals in decimal (no prefix), hexadecimal (prefix 0x) and octal (prefix 0) formats.
One possible alternative is to pass a binary string to the parseInt method along with the radix:
var foo = parseInt('1111', 2); // foo will be set to 15
In ECMASCript 6 this will be supported as a part of the language, i.e. 0b1111 === 15 is true. You can also use an uppercase B (e.g. 0B1111).
Look for NumericLiterals in the ES6 Spec.
I know that people says that extending the prototypes is not a good idea, but been your script...
I do it this way:
Object.defineProperty(
Number.prototype, 'b', {
set:function(){
return false;
},
get:function(){
return parseInt(this, 2);
}
}
);
100..b // returns 4
11111111..b // returns 511
10..b+1 // returns 3
// and so on
If your primary concern is display rather than coding, there's a built-in conversion system you can use:
var num = 255;
document.writeln(num.toString(16)); // Outputs: "ff"
document.writeln(num.toString(8)); // Outputs: "377"
document.writeln(num.toString(2)); // Outputs: "11111111"
Ref: MDN on Number.prototype.toString
As far as I know it is not possible to use a binary denoter in Javascript. I have three solutions for you, all of which have their issues. I think alternative 3 is the most "good looking" for readability, and it is possibly much faster than the rest - except for it's initial run time cost. The problem is it only supports values up to 255.
Alternative 1: "00001111".b()
String.prototype.b = function() { return parseInt(this,2); }
Alternative 2: b("00001111")
function b(i) { if(typeof i=='string') return parseInt(i,2); throw "Expects string"; }
Alternative 3: b00001111
This version allows you to type either 8 digit binary b00000000, 4 digit b0000 and variable digits b0. That is b01 is illegal, you have to use b0001 or b1.
String.prototype.lpad = function(padString, length) {
var str = this;
while (str.length < length)
str = padString + str;
return str;
}
for(var i = 0; i < 256; i++)
window['b' + i.toString(2)] = window['b' + i.toString(2).lpad('0', 8)] = window['b' + i.toString(2).lpad('0', 4)] = i;
May be this will usefull:
var bin = 1111;
var dec = parseInt(bin, 2);
// 15
No, but you can use parseInt and optionally omit the quotes.
parseInt(110, 2); // this is 6
parseInt("110", 2); // this is also 6
The only disadvantage of omitting the quotes is that, for very large numbers, you will overflow faster:
parseInt(10000000000000000000000, 2); // this gives 1
parseInt("10000000000000000000000", 2); // this gives 4194304
I know this does not actually answer the asked Q (which was already answered several times) as is, however I suggest that you (or others interested in this subject) consider the fact that the most readable & backwards/future/cross browser-compatible way would be to just use the hex representation.
From the phrasing of the Q it would seem that you are only talking about using binary literals in your code and not processing of binary representations of numeric values (for which parstInt is the way to go).
I doubt that there are many programmers that need to handle binary numbers that are not familiar with the mapping of 0-F to 0000-1111.
so basically make groups of four and use hex notation.
so instead of writing 101000000010 you would use 0xA02 which has exactly the same meaning and is far more readable and less less likely to have errors.
Just consider readability, Try comparing which of those is bigger:
10001000000010010 or 1001000000010010
and what if I write them like this:
0x11012 or 0x9012
Convert binary strings to numbers and visa-versa.
var b = function(n) {
if(typeof n === 'string')
return parseInt(n, 2);
else if (typeof n === 'number')
return n.toString(2);
throw "unknown input";
};
Using Number() function works...
// using Number()
var bin = Number('0b1111'); // bin will be set to 15
var oct = Number('0o17'); // oct will be set to 15
var oxx = Number('0xF'); // hex will be set to 15
// making function convTo
const convTo = (prefix,n) => {
return Number(`${prefix}${n}`) //Here put prefix 0b, 0x and num
}
console.log(bin)
console.log(oct)
console.log(oxx)
// Using convTo function
console.log(convTo('0b',1111))

Categories

Resources