I am trying to parse a hex value to decode a card
The hex data I receive from the card is f8b2d501f8ff12e0056281ed55
First I am converting this to an integer with parseInt()
var parseData = parseInt('f8b2d501f8ff12e0056281ed55', 16);
The value recieved is 1.9703930145800871e+31
When I try to decode this using the bitwise operator in Javascript
var cardNumber = ((parseData & 0xFFFFF) >> 1).toString();
I received a 0 value.
What am I doing wrong here, how can I parse the value of such large integer number?
There are two ways to do it:
First, notice that & 0xFFFFF operation in your code is just equivalent to getting a substring of a string (the last 5 characters).
So, you can just do a substring from the end of your number, and then do the rest:
var data = 'b543e1987aac6762f22ccaadd';
var substring = data.substr(-5);
var parseData = parseInt(substring, 16);
var cardNumber = ((parseData & 0xFFFFF) >> 1).toString();
document.write(cardNumber);
The second way is to use any big integer library, which I recommend to you if you do any operations on the large integers.
Since the number integer is so big you should use any bigNum library for js.
I recommend BigInteger, since you are working only with integers and it supports bitwise operations, however you can also check this answer for more options.
Related
In JS, I do have a float number which come from php as below:
var number = 2,206.00
In JS, I need to use parseFloat that number.
So I tried parseFloat(number), but its give only 2. So how can I get 2206.00 instead of 2?
Number.parseFloat is the same function object as globalThis.parseFloat.
If globalThis.parseFloat encounters a character other than:
a plus sign or,
a minus sign or,
a decimal point or,
an exponent (E or e)
...it returns the value up to that character, ignoring the invalid character and characters following it. A second decimal point also stops parsing.
So the following prints 2. And this seems to be your problem.
console.log(parseFloat('2,206.00')) // 2
Solution: use string manipulation to remove any commas from the number (really a String before parsing it.
console.log(parseFloat('2,206.00'.replaceAll(',', ''))) // 2206
If you need to store the value as a number but render it as a formatted string, you may need Number#toFixed to render the values after the decimal point:
console.log((2206).toFixed(2)) // '2206.00'
Final note: be careful about localization because some countries use commas for decimal points and decimal points for number grouping. As #t.niese says: store number values without localization, and then apply localization at the surface of your app. But that is a wider, more complicated topic.
You have to remove comma first and use parseFloat.
And about 2 decimal after dot, I see you use number_format($myNumber, 2) in PHP, so in JS, you use .toFixed(2).
var number = '2,206.00';
var result = parseFloat(number.replace(/,/g, '')).toFixed(2);
console.log(result);
First of all what you currently have most probably would trigger an Unexpected number error in JS.
It seems the generated value comes from the number_format() PHP function which returns a string. Moreover the var number variable should also be considered a string as we have a string format.
So firstly you should quote var number = '2,206.00' after that, you have to make the string float-like in order to parse it as float so we should replace , with empty string in order for the number to become 2206.00 number = number.replace(",",""). Lastly the parse should be done now in order to convert the float-like string to an actual float parseFloat(number).
Whole code:
var number = '2,206.00';
number.replace(",","");
number = parseFloat(number);
ok, basically you want a two decimal number after point like (20.03),
try this
parseFloat(number).toFixed(2)
I got a number 1267508826984464384 from json response. Here i print the number.
<script>
var num = 1267508826984464384;
console.log(num);
var num = "1267508826984464384";
console.log(num);
</script>
output is
In the first print the output is different from the original value. I need the same value as given.
Is it possible?
JavaScript uses floating point under the hood to store numbers. Floating point double precision, which is what JavaScript uses, can only store 64 bits of data. With the way numbers are represented in this manner, this means that there's a limit to how big a Number can normally be (2^53 - 1 for double precision floating point). Your number in the example has gone over this limit (overflow) and hence is being rounded by JavaScript.
You can use BigInt:
var num = BigInt(1267508826984464384);
console.log(num); // logs 1267508826984464384n, with n representing that it's a BigInt type
var num = "1267508826984464384";
console.log(num); // logs 1267508826984464384
May be helpful to read What Every Programmer Should Know About Floating-Point Arithmetic for more information on why this is the case.
They are different types (int and string, respectfully). What you are seeing in the top example is integer overflow (safely abstracted by JS). You can use a big integer to bypass this issue
const hugeString = BigInt("1267508826984464384")
console.log(hugeString + 1n) // 1267508826984464385n
The type of this is BitInt and it will safely allow you to represent your number as a integer. This type must be treated different and the additions must also be BigInt (as shown in the example above).
BigInt is a built-in object that provides a way to represent whole numbers larger than 253 - 1, which is the largest number JavaScript can reliably represent with the Number primitive and represented by the Number.MAX_SAFE_INTEGER constant. BigInt can be used for arbitrarily large integers.
From MDN. You can use it like so:
const theBiggestInt = 9007199254740991n
const alsoHuge = BigInt(9007199254740991)
// ↪ 9007199254740991n
const hugeString = BigInt("9007199254740991")
// ↪ 9007199254740991n
const hugeHex = BigInt("0x1fffffffffffff")
// ↪ 9007199254740991n
const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111")
// ↪ 9007199254740991n
RegEx for finding numbers and quoting them. Looks for prop value boundaries and a sequence of digits and optionally one period, and replaces inserting with quotes around the number value.
RegEx should be adjusted for maximum length or tolerances for numbers to be quoted as strings.
key or value prefix/suffix can be added, so that a JSON.parse reviver function can recognize them and parse to big.js or BigInt.
In most cases, you probably already know if you might receive a large number, and could probably just use a trivial RegEx replace on the specific property you need.
And, you should be coordinating with the server-side to give the data to you in another form that is safe to consume.
Parsing number strings using BigInt and big.js.
str = String.raw `{"j\"son":1234561251261262131231231231231231231231231232123123123,
"array":
[123123123124124214124124124124.111,
124124124124124124124124124,
124124124124124124124124
]}
`
str = str.replace(/((?:{|,|\[)\s*(?:"(?:[^"]|\\")+"\s*:\s*)?)(\d+\.?\d*)(\s*)(?=,|}|\])/g, `$1"$2"$3`)
// note: capture group $3 is just whitespace, which can normally be ignored; included to be "technically accurate"
console.log(
str,
(BigInt(JSON.parse(str)[`j"son`]) + 1n).toString(),
(Big(JSON.parse(str).array[0]).plus(0.0003)).toFixed()
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/big.js/5.2.2/big.min.js" integrity="sha256-gPNmhPlEOUlyAZomtrYRW/HSIjBOOl2LVxft3rsJpxI=" crossorigin="anonymous"></script>
I have a string below that is a price in £, I want to remove the currency symbol and then convert this into a number/price I can use to compare against another value (eg. X >= Y ...)
£14.50
I have previously converted strings to numbers used for currency with
var priceNum = parseFloat(price);
IDEAL OUTCOME
14.50 as a number value. Can this be done in a single line?
I found this very helpful
var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9\.-]+/g,""));
Convert (Currency) String to Float
If the currency symbol will always be there, just use substring:
var priceNum = parseFloat(price.substring(1));
If it may or may not be there, you could use replace to remove it:
var priceNum = parseFloat(price.replace(/£/g, ""));
Beware that parseFloat("") is 0. If you don't want 0 for an empty input string, you'll need to handle that. This answer has a rundown of the various way to convert strings to numbers in JavaScript and what they do in various situations.
Side note: Using JavaScript's standard numbers for currency information is generally not best practice, because if things like the classic 0.1 + 0.2 issue (the result is 0.30000000000000004, not 0.3). There are various libraries to help, and BigInt is coming to JavaScript as well (it's a Stage 3 proposal at the moment, currently shipping in Chrome). BigInt is useful because you can use multiples of your basic currency (for instance, * 100 for pounds and pence).
try this number-formatter-npm library. This library is fantastic.
npm i number-formatter-npm
documentation:https://www.npmjs.com/package/number-formatter-npm
I have on my server side (c#) an integer a:
int a = 65512;
and when I can cast it to short : (short)a is equal to -24
I want to move on this conversion to the client side (javascript)
I tried to convert it to first to binary : a.toString(2) and then do an a.toString(2) & 0xFF but in vain
How can I cast a number to a short one on javascript side ?
You can coerce a number in JavaScript to a particular numeric type by making use of TypedArray's, specifically, Int16Array:
function toShort(number) {
const int16 = new Int16Array(1)
int16[0] = number
return int16[0]
}
console.log(toShort(65512))
JavaScript doesn't have int and short and such, it has number, which is an IEEE-754 double-precision binary floating point type (and typed arrays as in Patrick Roberts' answer). However, for certain operations, it acts like it has a 32-bit integer type.
You could take your number and use bit shifting operators to lose half of that 32-bit value, like this:
var a = 65512;
a = (a << 16) >> 16;
console.log(a);
Another option is to understand that C# is overflowing the number so you can just check it's over the max value for a short which is 32767 (07FFF) and subtract the max value of an int+1 which is 65536 (0x10000). For example:
var number = 65512
var shortValue = number > 0x7FFF ? number - 0x10000 : number;
console.log(shortValue);
JavaScript does not support variable types such as short.
You'll have to handle ensuring the number is in short on the server side and keep it as a string in the JavaScript side.
There are a few Javascript functions available to convert anything into its equivalent number. Number() operates on an Object, valueOf(), parseFloat, parseInt() are also available.
I have an array which stores numbers 0-9 and decimal point, the elements of the array taken together represents a number. What is the best way to convert this array into a number, whole or fractional?
EDIT: Apologies if I were not clear before. The array, holding the 0-9 characters and possibly a decimal point, could represent either a whole number(without the decimal obviously) or a fractional number. So please suggest something that works for both cases. Thanks.
Try this
var a = [1,2,3,".",2,3];
var num = +a.join("");
What is the best way to convert this array into a number, whole or fractional?
Firstly to combine your array elements you should use Array.join().
You will then have a concatenated variable of your values and decimal. To convert this to a whole number, use parseInt(), and to a floating point number use parseFloat(). You can use the unary + operator (which acts similarly to parseFloat), however in my opinion it is not the best choice semantically here, as you seem to want a specific type of number returned.
Example:
var arr = ['1','.','9','1'];
var concat = arr.join();
var whole = parseInt(concat);
var floating = parseFloat(concat);
Also, parseInt will trim the decimal portion of your number, so if you need rounding you can use:
var rounded = Math.round(parseFloat(concat));
You could use the split property of the string. It splits all the characters into an zero based array.
var charSplits = "this is getting split.";
var splitArr = charSplits.split();
Console.log(splitArr);
// this returns i
Console.log(splitArr[2]);