Unable to convert a string to integer [duplicate] - javascript

This question already has answers here:
How can I check if a string is a valid number?
(50 answers)
Closed 4 years ago.
I have an AJAX request in my page and the .php page echoes an integer or string based on the event in the page. But, when the variable reaches to my actual javascript file , it becomes string. For example 4 changes to "4". And that is making my program problematic because my program has to run according to the responseText. I have a XMLHTTPRequestObject.onload function that works like:
if(typeof XMLHTTPRequest.responseText === "number"){
// do something
}
My php script provides a result either integer or string and if the result is string, then I can perform the function but it is not happening like so. I tried changing the variable using parseInt() and Number() but then, everything gets changed to number either it was s string. So, how do I tackle this problem? Please do help!

You can try converting the string to number using Number. If you receive NaN you know the string wasn't a valid number say 123notANumber for example, see here for more information.
if (isNaN(Number('123test')) {
// This is a string
}
else {
// It's a number
}

As mentioned in the comments XMLHttpRequest.responseText will always be a string. The easiest solution is likely to use the Number constructor to convert that string to a number. If the string doesn't represent an integer, Number will return NaN. So instead of what you have currently, you could do somthing like this:
const parsed = Number(XMLHTTPRequest.responseText);
if(isNaN(parsed)){
//handle case where response is a string
} else {
//handle case where response is a number
}

Related

What exactly is (alert(1),"") in javascript [duplicate]

This question already has answers here:
What does the comma operator do in JavaScript?
(5 answers)
Closed 2 years ago.
I tried doing google gruyeres XSS challenges (http://google-gruyere.appspot.com/part2), and at the stored AJAX XSS challenge they have the following code part for the JSON response:
all <span style=display:none>"
+ (alert(1),"")
+ "</span>your base
The interesting part is: (alert(1),"")
According to the solution provided, the empty string gets returned. According to my testing, the alert(1) still gets exectued.
Is this some sort of function shorthand, or what would this be called in JS?
Why does it execute the alert, but then return the empty string?
Thank you very much for any help!
Best regards,
Rolf
This is the comma operator. The code executes alert(1), discards its return value, then evaluates "". Since this is the last item in the expression, its value is returned, which is empty string.
The tutorial I linked describes it as follows:
The comma operator in JavaScript evaluates each of its operands. It returns the value of the last operand. Add multiple expressions using the comma operator.

JavaScript test if number variable is a number [duplicate]

This question already has answers here:
Validate decimal numbers in JavaScript - IsNumeric()
(52 answers)
Closed 5 years ago.
I’m loading a JSON file a reading the values into an array using a for loop
I’m concerned that sometimes the JSON file might become corrupted ie the values Im reading in might become ASCII letters ie 1t3 where the value should of been 123
Is there a test case where you could say if values[a] does not equal a number then set it to “ “ or blank
Thanks,
Ben
You could use the parseInt() function and check if it returns an integer or NaN. You can check out information on it on W3schools or the MDN Web Docs.
However, in my opinion, it would be better to use regular expressions. If you read the w3schools examples for parseInt(), they show that "0x10" is read as 16.
For a regular expression, try the following:
function isNumber(n) {
// Added checking for period (in the case of floats)
var validFloat = function () {
if (n.match(/[\.][0-9]/) === null || n.match(/[^0-9]/).length !== 1) {
return false;
} return true;
};
return n.match(/[^0-9]/) === null ? true : validFloat();
}
// Example Tests for Code Snippet
console.log(isNumber("993"));
console.log(isNumber("0t1"));
console.log(isNumber("02-0"));
console.log(isNumber("0291"));
console.log(isNumber("0x16"));
console.log(isNumber("8.97"));
The MDN Web Docs have a super helpful page on Regular Expressions.

Int entered verificatiion - Parse Server Cloud Code

I use the new Parse Server, and in the cloud part which is using Javascript I want to check if an integer is specified by a user, in other words I want to check if the Int is null or not. I can do it for strings, but as I see from comments, an int can not be null. Bu I do not want to change all ints in my code to integers. I try the code below, but it is not working, how can I check if there is a number specified by the user or if it is empty?
if (!req.object.get('number'))
Your code should work as long as number isn't zero. To handle that case as well, simply do a type check like this:
if (typeof req.object.get('number') !== 'number').
It seems like you are confusing java and javascript. Javascript does not have ints or integers, only numbers. Javascript variables do not have types and all variables can be null and undefined.

Big JavaScript ints won't cast to String without rounding

I am trying to pass a big int to a function from an onclick event in HTML. The ints are always very long, and I cannot seem to pass it to my function without rounding. I have tried some bigInt libraries to the same end, though I would much rather prefer simple string casting.
My js function:
function initBuy(id){
console.log(id.toString());
}
and my HTML event:
<dt></dt><dd><a id="buy" onclick="initBuy(String(' + all_data[index].listing_id + '))" class="btn btn-success">Buy This Item</a></dd>
An example of a passed int:
13934317650292905813
and the result of clicking the button:
"13934317650292906000"
The passed int looks fine when I write it to an elements' text. When I pass it to a function, however, it's rounding it.
From the post here the maximum value an integer in Javascript could take is 9007199254740992
Your number 13934317650292905813 is far bigger than that.
From this post here you can use BigInteger.js to accommodate big integers
You say in your (ambiguous) question:
'The passed int looks fine when I write it to an elements' text. When I pass it to a function, however, it's rounding it.'
and in your comment:
If I set all_data[index].listing_id to an elements text, it works.
That means you are already getting the 'integer' as text-string in JSON.
Nothing in your current question converts the string to a number (I tested it).
As soon as the string would be converted to a number it would overflow IEEE 754's max accuracy of 2^53=9007199254740992.
Note that: initBuy(String(' + all_data[index].listing_id + '))
will return the string + all_data[index].listing_id + (as it should).
Passing the string '13934317650292905813' to your initBuy function also returns string '13934317650292905813' (as it should).
In other words, I can not reproduce your problem using the code you have supplied.
I assume you have simplified your initBuy function for this question (you'd have to post the original one for further examination, preferably together with an excerpt of a relevant part of the raw JSON string).
I assume you might accidentally convert the string to a number (probably using a +) inside that function!

javascript now to create two ways currency format? [duplicate]

This question already has answers here:
How to convert a currency string to a double with Javascript?
(23 answers)
Closed 8 years ago.
I have found this link have a simple and useable funciton to convert number to currency.
www.mredkj.com/javascript/nfbasic.html
but how to turn it back form currency to number...
I already try this :
[http://jsfiddle.net/vb2cb1tm/3/]...
But its failed...
I try to read a formatted string using javascript and make a counting on this valua...
I think something as simple as
function numbers(nStr){
return Number(nStr.replace(/[\$\,]/g,''));
}
might do the trick, though it's hard to tell without seeing your original code.
function cur2num(cur) {
return parseFloat(cur.replace(/,/g,"");
}
if currency signs try /[^0-9]\.\-]/g as first argument to the replace

Categories

Resources