How to convert BigInt to Number in JavaScript? - javascript

I found myself in the situation where I wanted to convert a BigInt value to a Number value. Knowing that my value is a safe integer, how can I convert it?

Turns out it's as easy as passing it to the Number constructor:
const myBigInt = BigInt(10); // `10n` also works
const myNumber = Number(myBigInt);
Of course, you should bear in mind that your BigInt value must be within [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER] for the conversion to work properly, as stated in the question.

You can use parseInt or Number
const large = BigInt(309);
const b = parseInt(large);
console.log(b);
const n = Number(large);
console.log(n);

Edit: see the discussion in the comments below as to why this answer is not correct. I am leaving the answer up regardless for disambiguation.
You should use either of the static methods:
BigInt.asIntN() - Clamps a BigInt value to a signed integer value, and returns that value.
BigInt.asUintN() - Clamps a BigInt value to an unsigned integer value, and returns that value.
as documented here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#static_methods

Related

JavaScript: parseFloat() strips trailing zeros

I have been trying to find a solution to the following problem. I have a string that is a floating-point number like,
var value = '12.30';
When I try to cast it to be a floating number
parseFloat('12.30'); // output is 12.3
I need a way for my logic to return 12.30, the actual value, and that too a number.
Solutions I checked used,
parseFloat('12.30').toFixed(2);
but this converts it to string type and that's not acceptable in my scenario.
Any help would be appreciated. Thanks!
It's not parseFloat()'s fault. Numerically speaking, 12.30 equals 12.3, even if you don't use parseFloat():
const x = 12.30;
console.log(x); // Prints "12.3"
You can just use unary plus from Type Conversions in JavaScript for get number value
var value = '12.30';
alert(parseFloat(value).toFixed(2)); // 12.30
alert(typeof +parseFloat(value).toFixed(2)); // number
Get new successess in development!

how to handle more than 20 digit number (Big integer)?

My angular program, I need to pass the number which is more than 20 digit to the API request.
num: any;
this.num = 2019111122001424290521878689;
console.log(this.num); // It displays "2.0191111220014244e+27"
I tried to change string from number as below
console.log(this.num.toString()); // It displays "2.0191111220014244e+27"
My expectation is that I need to pass the original big integer into the API request. If I pass as below, it goes as "2.0191111220014244e+27".
BTW, I tried BigInt(this.num), which gives difference number.
Suggest me
In JavaScript, big integer literals have the letter n as a suffix:
var bigNum = 2019111122001424290521878689n;
console.log(bigNum);
For more information, see
MDN JavaScript Reference - BigInt
If you got a large number (> SAFE_INTEGER) from an API, in JSON format, and you want to get the exact value, as as string, you unfortunately can't use JSON.parse(), as it will use the number type and lose precision.
There are alternative JSON parsers out there like LosslessJSON that might solve your problem.
You can use BigInt.
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. BigInt can be used for arbitrarily large integers.
const theBiggestInt = 9007199254740991n;
const alsoHuge = BigInt(9007199254740991);
// ↪ 9007199254740991n
const hugeString = BigInt("9007199254740991");
// ↪ 9007199254740991n
const hugeHex = BigInt("0x1fffffffffffff");
// ↪ 9007199254740991n
const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
// ↪ 9007199254740991n
BigInt is similar to Number in some ways, but also differs in a few key matters — it cannot be used with methods in the built-in Math object and cannot be mixed with instances of Number in operations; they must be coerced to the same type. Be careful coercing values back and forth, however, as the precision of a BigInt may be lost when it is coerced to a Number.
Refer to
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt
The problem is that the number you have there is not an integer. Javascript can only store integers up to the value given by Number.MAX_SAFE_INTEGER. In chrome, this number is 9007199254740991.
The number you have is actually a floating point number, and converting it between floating point and integer will loose some precision.

Parseint – truncating with e+

I am using parseInt() internally to convert a value that I now want to convert to another number system with toString().
parseInt(value, 10).toString(16)
But since the integer is being truncated (ie 1.7956279830335669e+47) because of length, I am unable to achieve the desired hexadecimal representation of my number.
Is there some other way to cast a string to an int?
How can I go about resolving this?
Use BigInt:
BigInt(value).toString();
You need it because the largest Number JavaScript can support is 9007199254740991:
console.log(Number.MAX_SAFE_INTEGER);
You can use BigInt because it's a built-in global object, however it's not a fully supported ECMAScript feature - currently it's in Stage 3 of development.
Try (works on chrome where BigInt is supported)
BigInt(Number(value)).toString(16);
however using this approach we loose precision but we can use alternative approach by convert number in exponential form to integer form
let value= "1.7956279830335669e+47";
let sim = BigInt(Number(value)).toString(16);
let prec = BigInt(fix2IntStr(value)).toString(16);
let direct = 179562798303356690000000000000000000000000000000n.toString(16);
// convert "exponential" form to integer string
function fix2IntStr(str) {
let [m,e] = value.split('e');
e = e - (m.length - m.indexOf('.')-1);
m = m.replace('.','');
return m+"0".repeat(e);
}
console.log('simple :', sim);
console.log('precise:',prec);
console.log('direct :',direct);

Why I can't convert string to number without losing precision in JS?

We all know that +, Number() and parseInt() can convert string to integer.
But in my case I have very weird result.
I need to convert string '6145390195186705543' to number.
let str = '6145390195186705543';
let number = +str; // 6145390195186705000, but should be: 6145390195186705543
Could someone explain why and how to solve it?
Your number is above the Number.MAX_SAFE_INTEGER (9,007,199,254,740,991), meaning js might have a problem to represent it well.
More information
You are outside the maximum range. Check in your console by typing Number.MAX_SAFE_INTEGER
If you want a number outside this range, take a look into BigInt that allows to define numbers beyond the safe range
https://developers.google.com/web/updates/2018/05/bigint
Read the documentation well before using it since the usage is different than usual
I am guessing this is to solve the plusOne problem in leetcode. As others have answered, you cannot store value higher than the max safe integer. However you can write logic to add values manually.
If you want to add one to the number represented in the array, you can use the below function. If you need to add a different value, you need to tweak the solution a bit.
var plusOne = function(digits) {
let n = digits.length, carry=0;
if(digits[n-1]<9){
digits[n-1] +=1;
} else{
digits[n-1] = 0;
carry=1;
for(let i=n-2;i>=0;i--){
if(digits[i]<9){
digits[i]+=1;
carry=0;
break;
}else{
digits[i]=0;
}
}
if(carry>0){
digits.unshift(carry);
}
}
return digits;
};
Short answer: Your string represents a number to large to fit into the JavaScript number container.
According to the javascript documentation the maximum safe number is 2^53 which is 9007199254740992 source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
When you try and convert your number you're creating an overflow exception so you get weird results.

Is using parseInt extraenous if unnecessary?

I am a beginner to coding and JavaScript but I am doing a practice exercise and I came across something I am unsure about.
var nameLength = parseInt(fullName.length);
var nameLength = fullName.length;
I used the first line not even thinking it would already be an integer, so should I still have included the parseInt or not?
Yes, remove var nameLength = parseInt(fullName.length); Below is your explanation:The parseInt() method in JavaScript is used to turn the integer value of a string into an integer. If I have string, say var s = "3";, I could use the + operator to it, but it wouldn't add as if they were numbers (ex. s += 9;, then s would equal "39"). You call the parseInt() method only if you have a value with the type of string. In your case, and in most, if not all languages, the .length or .length() of anything will return an integer. What you're doing is trying to convert a number to a number, which is (after I googled the definition) extraneous.

Categories

Resources