Parseint – truncating with e+ - javascript

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);

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.

Conversion issue for a long string of integers in JavaScript

I'm trying to convert a long string which has only integers to numbers.
var strOne = '123456789123456789122';
parseInt(strOne, 10);
// => 123456789123456800000
var strTwo = '1234567891234567891232';
parseInt(strTwo, 10);
// => 1.234567891234568e+21
The expected output should be the same as strOne and strTwo but that isn't happening here. While converting the string to a number, the output gets changed.
What's the best way to fix this issue?
BigInt is now available in browsers.
BigInt is a built-in object that provides a way to represent whole
numbers larger than 253, which is the largest number JavaScript can
reliably represent with the Number primitive.
value The numeric value of the object being created. May be a string or an integer.
var strOne = '123456789123456789122';
var intOne = BigInt(strOne);
var strTwo = '1234567891234567891232';
var intTwo = BigInt(strTwo);
console.log(intOne, intTwo);
You number is unfortunately too large and gets wrapped when the conversion is done.
The largest integer you can express in JavaScript is 2^53-1, it is given by Number.MAX_SAFE_INTEGER, see the MDN doc here.
The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(2^53 - 1) and 2^53 - 1.
console.log(Number.MAX_SAFE_INTEGER);
If you want to work with numbers bigger than this limit, you'll have to use a different representation than Number such as String and use a library to handle operations (see the BigInteger library for example).

How to convert BigInt to Number in 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

How do i take user input and convert the string into an integer that i can use mathematically in a function?

How do i take user input and convert the string into an integer that i can use mathematically in a function??
Totally new to coding and trying to build a simple calculator. I am not sure what i am doing wrong, any help would be appreciated.
function TLV()
{
var TLVday = Integer.valueOf("getTLVdate");
var OBday = Integer.valueOf("getOBdate");
if (TLVday<OBday)
{
DD = OBday + 10;
}
else
{
DD = OBday + 30;
}
document.getElementById("TLVoutput").innerHTML=DD;
}
<form name="myform" id="frm1">
<table style="border:0;">
<tr>
<td>OB Start Day:</td>
<td><input type="text" id="getOBdate"/></td>
</tr>
<tr>
<td>TLV Start Day: </td>
<td><input type="text" id="getTLVdate"/></td>
<td id="TLVoutput"></td>
</tr>
<button onclick="TLV()">Calculate</button>
</table>
</form>
Here are three common ways:
var myNumber = +myString; // coerce string to number
var myFloat = parseFloat(myString); // parse as floating point number
var myInt = parseInt(myString, 10); // parse as a base-10 integer
Documentation:
+ operator - mdn msdn
parseFloat() method - mdn msdn
parseInt() method - mdn msdn
Each of these techniques have their own quirks. Because of the dynamic nature of JavaScript, type conversion is not simple.
parseInt()
parseInt() produces either an integer or a NaN by reading the digits from left to right. If your string contains only numeric digits, and you are using a browser that supports ECMAScript 5 (IE8 and older do not), It is very straightforward - you get those digits as a number in base 10. In IE8 or older, if the first digit is 0, you'll get the number in octal. Eg, parseInt("010") returns 10 in modern browsers and 8 in older browsers. To correct for this, always specify the radix in the second parameter. parseInt("010", 10) always returns 10, regardless of browser version.
Parsing stops at the first non-digit character. So, parseInt("4 donuts") returns 4 as does parseInt("4,000"). If the first character in the string is not a digit or + or -, you will get NaN, so you can't parse "$5".
If the string starts with 0x it is treated as Hexadecimal (base 16). parseInt("0x10") returns 16. Same thing if you explicitly specify base 16 with the radix: parseInt("10", 16).
parseFloat()
parseFloat() is similar to parseInt(). The differences are that parseFloat() only works with base 10, and, obviously, it produces a floating point number.
Addition operator (+)
In JavaScript, a string can be used as a number. When a JavaScript construct accepts a number and gets something else (such as a string), it very typically tries to "coerce" it to a number. One case where we see this behavior is the + operator. In some ways, coercion is more strict than parsing -- The entire string must be numeric, not just the beginning, or else it returns NaN. But, in another way, it's less strict -- an empty or whitespace string returns 0 when coerced to a number, but returns NaN when parsed.
Besides the addition operator, other ways to coerce a string to a number include:
Use the Number() constructor as a function
Pass a string to a method that accepts a number, eg Math.floor("10")
Use a string with an arithmetic operator:
var string = "10";
var num = string * 1;
var num = string / 1;
Get the full details about how a string is coerced to a number in the ECMAScript Spec, Section 9.3.1.
There is no such thing as 'Integer', that's Java not JavaScript.
To parse a string into an integer, you can use parseInt, but if you don't care whether it's an integer or floating-point there's no need to do anything - it will automatically convert when you try to use it.
However, you cannot access a field value just by using its id. Instead you must use the DOM - 'document.getElementById("getTVLdate").value'
Use parseInt('value', 10 ) to convert a string to a number
To read the value use this syntax .. Where it selects the element based on the id and then use the value property on it to get the value.
Remember this is JavaScript and not Java
var TLVday = document.getElementById.('getTLVdate').value
Change your code to
var button = document.getElementById('calculate');
button.addEventListener('click', TLV);
function TLV() {
var TLVday = parseInt(document.getElementById('getTLVdate').value, 10),
OBday = parseInt(document.getElementById('getOBdate').value, 10),
DD = 0;
if (TLVday < OBday) {
DD = OBday + 10;
} else {
DD = OBday + 30;
}
document.getElementById("TLVoutput").innerHTML = DD;
}
Also avoid binding events inline. Always a better idea to separate your concerns.
Check Fiddle
If you have a string you need converted to a number you can use parseInt , parseFloat if you need a floating point.
parseInt('84945');
You can give another parameter parseInt('84945',10); to specify the base, bas 10 in this case

Categories

Resources