From character to binary (adding the left 0) - javascript

You can convert from char to binary in JS using this code:
var txt = "H";
bits = txt.charCodeAt(0).toString(2); //bits=1001000
The result is mathematically correct but no literally, i mean, there is a missing 0 to the left, that again, is correct, but I wonder if there is a way to make it consider the left zeros.

You need a byte? Try this:
var txt = "H",
bits = txt.charCodeAt(0).toString(2),
aByte = new Array(9 - bits.length).join('0') + bits;
The snippet creates a new array with length of missing bits + 1, then it converts the newly created array to a string with amount of zeroes needed. 9 is the wanted "byte length" + 1.
However, this is relatively slow method, if you're having a time-critical task, I'd suggest you to use while or for loop instead.

charCodeAt() returns the code of a character, which is a general number.
A number itself does not have any kind of preffered alignment.
By convention numbers are printed without any leading zeros.
In fact, charCodeAt() returns unicode character code,
which in general can take more than 8 bits to store.
Therefore such behaviour is correct.

Try this
var bits = txt.charCodeAt( 0 ).toString( 2 );
var padding = 8 - bits.length;
res = [ ];
res.push( new Array( padding+1 ).join( '0' ) + bits );

Related

Numeric Regex Expression for Detection Using Javascript

I am completely new to regex hence the long question.
I would like to know about the regex expression codes to detect different types of numbers in a html paragraph tag.
Integer number (eg: 0 , 1,000 , 1000 , 028, -1 , etc)
Floating number (eg: 2.3 , 2.13 , 0.18 , .18 , -1.2 , etc)
or regex that can combine both 1. & 2. -- all integer and float number together will be so good! I tried some solution in Stackoverflow but the results are always undefined/null, else not detectable already
Ratio (eg: 1:3:4 detect as a whole if possible)
Fractional number (eg: 0/485 , 1/1006 , 2b/3 , etc)
Percentage number (eg: 15.5% , (15.5%) , 15% , 0.9%, .9%)
Also, would like to know if regex can detect symbols and numbers together in a whole (15.5% , 1:3:4), or must they be split into different parts before the detection of number can be performed (eg: 15.5 + % , 1 + : + 3 + : + 4 ) ?
These different expressions are meant to be written into Javascript code as different exceptions of cases later on. The expressions are planned to be used like the regex that detects basic integer in attached Javascript snippet below:
var paragraphText = document.getElementById("detect").innerHTML;
var allNumbers = paragraphText.match( /\d+/g ) + '';
var numbersArray = allNumbers.split(',');
for (i = 0; i < numbersArray.length; i++) {
//console.log(numbersArray[i]);
numbersArray[i] = "<span>" + numbersArray[i] + "</span>";
console.log(numbersArray[i]);
}
});
Thank you very much for your help!
The following are simple implementations:
'2,13.00'.match(/[.,\d]+/g) // 1 & 2
'1:3:4'.match(/[:\d]+/g) // 3
'0/485'.match(/[\/\d]+/g) // 4
'15.5%'.match(/[.%\d]+/g) // 5
You can loop through them using for statement, and check if one is detected and break, or continue otherwise.
For decimals numbers:
-> ((?:\d+|)(?:\.|)(?:\d+))
For percentage numbers : It is the same as decimal numbers followed by % symbol
-> ((?:\d+|)(?:\.|)(?:\d+))%
For whole numbers: the following regex would work and would exclude any decimal numbers as well, returning you just the integers
-> (^|[^\d.])\b\d+\b(?!\.\d)
For the ration requirement, I have created a complicated one, but you would get the entire ratio as a whole.
-> (((?:\d+|)(?:\.|)(?:\d+)):)*((?:\d+|)(?:\.|)(?:\d+))

JavaScript flooring number to order of magnitude

I want to floor any integers >= 10 according to its order of magnitude. For instance,
15 -> 10
600 -> 100
8,547 -> 1,000
32,123 -> 10,000
3,218,748 -> 1,000,000
544,221,323,211 -> 100,000,000,000
....
I was thinking parsing the int to string and count how many digits are there, then set the new string to 1 + a bunch of zeros and convert back to number.
function convert(n) {
nStr = n.toString();
nLen = nStr.length;
newStr = "1" + Array(nLen).join("0");
return parseInt(newStr);
}
Is there a more mathematical way to do this? I want to avoid converting between int and str because it might waste a lot of memory and disk space when n is huge and if I want to run this function a million times.
So you're looking for the order of magnitude.
function convert(n) {
var order = Math.floor(Math.log(n) / Math.LN10
+ 0.000000001); // because float math sucks like that
return Math.pow(10,order);
}
Simple ^_^ Math is awesome! Floating point imprecisions, however, are not. Note that this won't be completely accurate in certain edge cases, but it will do its best.

Javascript String to int conversion

I have the following JS immbedded in a page:
var round = Math.round;
var id = $(this).attr("id");
var len = id.length;
var indexPos = len -1; // index of the number so that we can split this up and used it as a title
var pasType = id.substring(0, indexPos); // adult, child or infant
var ind = round(id.substring(indexPos)); // converts the string index to an integer
var number = (id.substring(indexPos) + 1); // creates the number that will go in the title
window.alert(number);
id will be something like adult0, and I need to take that string and split it into adult and 0 - this part works fine.
The problem comes in when I try to increment the 0. As you can see I use Math.round to convert it to an integer, and then add 1 to it - I expect 0 to be 1 after this. However, it doesn't seem to be converting it to integer, because I get 01, not 1. When testing this with adult1 the alert I get is 11.
I'm using this question for reference, and have also tried var number += id.substring(indexPos);, which breaks the JS (unexpected identifier '+=')
Does anyone know what I'm doing wrong? Is there a better way of doing this?
The parseInt() function parses a string and returns an integer,10 is the Radix or Base
[DOC]
var number = parseInt(id.substring(indexPos) , 10 ) + 1;
This is to do with JavaScript's + in operator - if a number and a string are "added" up, the number is converted into a string:
0 + 1; //1
'0' + 1; // '01'
To solve this, use the + unary operator, or use parseInt():
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
The unary + operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt() is self-explanatory (converts into number, ignoring decimal places).
The second argument is necessary for parseInt() to use the correct base when leading 0s are placed:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
There's also parseFloat() if you need to convert decimals in strings to their numeric value - + can do that too but it behaves slightly differently: that's another story though.
Convert by Number Class:-
Eg:
var n = Number("103");
console.log(n+1)
Output: 104
Note:- Number is class. When we pass string, then constructor of Number class will convert it.
JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:
var numberAsInt = parseInt(number, 10);
// Second arg is radix, 10 is decimal.
If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.
Although parseInt is the official function to do this, you can achieve the same with this code:
number*1
The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.
Use parseInt():
var number = (parseInt(id.substring(indexPos)) + 1);` // creates the number that will go in the title
If you are sure id.substring(indexPos) is a number, you can do it like so:
var number = Number(id.substring(indexPos)) + 1;
Otherwise I suggest checking if the Number function evaluates correctly.

numbers and toFixed , toPrecision in Javascript?

Regarding the famous issue of 1.01+1.02 which is 2.0300000000000002
one of the workarounds is to use toFixed : e.g.
(1.01+1.02).toFixed(2) --->"2.03"
But I saw a solution with toPrecision
parseFloat((1.01+1.02).toPrecision(10))-->"2.03"
But lets have a look at n in
toFixed(n)
toPrecision(n)
How would I know what is n ?
0.xxxxxxxxxxx
+
0.yyyyyyyyyyyyy
---------------------
0.zzzzzzzzzzzzzzzzzzzzzzzzz
^
|
-----??????------
each number being added can have a different decimal digits...
for example :
1.0002+1.01+1.03333--> 3.0435300000000005
how would I calculate the n here ? what is the best practice for this (specific) issue ?
For addition as in this situation I would check the number of decimal places in each operand.
In the simplest of situations the number of decimal places in the operand with the greatest number of decimal places is the value of n.
Once you have this, use which ever method you like to truncate your value. Then get rid of trailing zeros.
You may encounter trailing zeros in situations such as 1.06 + 1.04, the first step would take you to 1.10 then truncating the zero would give 1.1
In your last example 1.0002+1.01+1.03333 greatest number of decimal places is 5 so you are left with 3.04353 and there are no trailing zeros to truncate.
This returns the expected output:
function add(){
// Initialize output and "length" properties
var length = 0;
var output = 0;
// Loop through all arguments supplied to this function (So: 1,4,6 in case of add(1,4,6);)
for(var i = 0; i < arguments.length; i++){
// If the current argument's length as string is longer than the previous one (or greater than 0 in case of the first argument))
if(arguments[0].toString().length > length){
// Set the current length to the argument's length (+1 is to account for the decimal point taking 1 character.)
length = arguments[0].toString().length +1;
}
// Add the current character to the output with a precision specified by the longest argument.
output = parseFloat((output+arguments[i]).toPrecision(length));
}
// Do whatever you with with the result, here. Usually, you'd 'return output;'
console.log(output);
}
add(); // Returns 0
add(1,2,3); // Returns 6
add(1.01,2.01,3.03); // Returns 6.05
add(1.01,2.0213,3.3333); // Returns 6.3646
add(11.01,2.0213,31.3333); // Returns 44.3646
parseFloat even gets rid of trailing zero's for you.
This function accepts as many numbers as parameters as you wish, then adds these together taking the numbers' string length into account, when adding them. The precision used in the addition is dynamically modified to fit the "currently added" argument's length.
Fiddle
If you're doing calculations, you have a couple of choices:
multiply the numbers by eg 100, to convert to integers, then do the calculations, then convert back again
do the calculations, dont worry about the rounding errors, then round the result at display time
If you're dealing with money/currencies, the first option is probably not a bad option. If you're just doing scientific maths, I would personally not worry about it, and just round the results at display time, eg to 6 significant figures which is the default for my c++ compiler (gcc; not sure if it is in the c++ standards or not, but if you print 1.234567890 in gcc c++, the output is 1.23457, and the problem is avoided)
var a = 216.57421;
a.toPrecision(1); // => '200' because 216 with 1 < 5;
a.toPrecision(2); // => '220' because 216 with 6 >= 5;
a.toFixed(1); // => 216.6 because 7 >= 5;
a.toFixed(2); // => 216.57 because 4 < 5;

Javascript parsing int64

How can I convert a long integer (as a string) to a numerical format in Javascript without javascript rounding it?
var ThisInt = '9223372036854775808'
alert(ThisInt+'\r' +parseFloat(ThisInt).toString()+'\r' +parseInt(ThisInt).toString());
I need to perform an addition on it before casting it back as a string & would prefer not to have to slice it two if at all possible.
All Numbers in Javascript are 64 bit "double" precision IEE754 floating point.
The largest positive whole number that can therefore be accurately represented is 2^53 - 1. The remaining bits are reserved for the exponent.
Your number is exactly 1024 times larger than that, so loses 3 decimal digits of precision. It simply cannot be represented any more accurately.
In ES6 one can use Number.isSafeInteger( # ) to test a number to see if its within the safe range:
var ThisInt = '9223372036854775808';
console.log( Number.isSafeInteger( parseInt( ThisInt ) ) );
There is also a BigInteger library available which should be able to help, though, and avoid you having to do all the string and bit twiddling yourself.
EDIT 2018/12 there's now a native BigInt class (and new literal syntax) landed in Chrome and NodeJS.
With a little help from recursion, you can directly increment your decimal string, be it representing a 64 bit number or more...
/**
* Increment a decimal by 1
*
* #param {String} n The decimal string
* #return The incremented value
*/
function increment(n) {
var lastChar = parseInt(n.charAt(n.length - 1)),
firstPart = n.substr(0, n.length - 1);
return lastChar < 9
? firstPart + (lastChar + 1)
: firstPart
? increment(firstPart) + "0"
: "10";
}
You cannot do this with standard Javascript. But as always, there is a nifty little library to help us out, in this case BigInt.js, which will let you use arbitrary-precision integers.
Have you tried using the Number class?
var num = new Number(parseFloat(ThisInt))
Just use Number(ThisInt) for this instead of Int or float

Categories