Javascript parseInt not working on a string, trying to get an integer from an HTML value - javascript

I am making a basic game, and I have a tile system that I'm using. Each tile has an ID of "tileX", where X is a number (ex. tile1). I have a function as follows:
window.onclick = function() {
var x = event.clientX, y = event.clientY,
elementMouseIsOver = document.elementFromPoint(x, y).id;
document.getElementById("tileTell").value = elementMouseIsOver;
console.log(elementMouseIsOver);
console.log(typeof(elementMouseIsOver));
elementMouseIsOver = parseInt(elementMouseIsOver);
console.log(elementMouseIsOver);
console.log(typeof(elementMouseIsOver));
}
Line 4 of code there fills in an input field so I can visually see which tile I've clicked (I'm using this to make sure things are working properly and so I can find the tiles I need). That works fine. On line 5 when I do a console.log, it gives me the proper ID, and verifies that it is a string.
After that I want to reset the elementMouseIsOver variable to be an integer, so if the ID was tile1 I would expect the new result to be 1. But when I look at it in the console, I get NaN. And then when I check the type of it immediately after that, I get number.
The parseInt does not seem to be working properly, what am I doing wrong? I need to use the ID names of each tile for mathematical operations so this is vital to my game. I know it's probably a really dumb mistake but I am completely at a loss...

If you want parseInt() to work on strings in the way you're using it, it has to start with a digit; in your case, it starts with alphabetical characters, and so (with an implicit radix of 10) it will rightfully return NaN.
You could get the number out by using a generic method:
var num = +(elementMouseIsOver.match(/\d+/) || [])[0];
It matches the first group of digits it can find and then uses the unary plus operator to cast it into an actual number value. If the string doesn't contain any digits, it will yield NaN.
In your particular case, you could also apply parseInt() on the part that immediately follows "tile":
var num = +elementMouseIsOver.substr(4);

NaN is correct.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.
Nothing parsed successfully.
EDIT
You could accomplish what you want by removing the non-numeric characters from the string, assuming you'll always have a string+integer as the ID. Try this:
parseInt(elementMouseIsOver.replace(/[^\d]/,""))

You need to remove the "tile" string first, so it can properly parse the value:
elementMouseIsOver = parseInt(elementMouseIsOver.substring("tile".length));
.substring("tile".length) returns a substring starting with the character after "tile" (position 4 in the string, count starts at 0), resulting in only the number of the ID (as a string).
fiddle: http://jsfiddle.net/rk96uygd/

The typeof of a NaN is number.
Use isNaN() to test if a value is NaN or Not a Number
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
You could also use the Number() cast instead of parseInt().

you trying to parseInt on a element ID that is non-numeric, when parse fail it will return NaN (*or not a number*)
elementMouseIsOver = parseInt(elementMouseIsOver);
moreover, your elementMouseIsOver is an ID of control, I don't think .value can get the value of control
elementMouseIsOver = document.elementFromPoint(x, y).id;

Related

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.

String To Number Confusion

Why does parseInt("-1000-500-75-33") return -1000?
Shouldn't it return the sum of those numbers: -1608
How can I get the string "-1000-500-75-33" to return as the sum of those numbers?
parseInt will try to get a number starting from the beginning of the string.
Since - is a valid character to begin a number with, it parses the string until it finds something invalid. The second - is invalid because no integer can contain an - inside it, only digits. So it stops there and considers the number to be "finished".
Now, if you want to process the expression, you can use eval like so:
eval("-1000-500-75-33")
This will return -1608 as expected.
parseInt will not perform any computations, rather it will try to convert a string into an integer. It returns -1000 because the dash afterwards would not be considered a valid number. If you want to sum all these numbers you could split on the dash, map to Number, then reduce:
var numString = "-1000-500-75-33";
numString.split('-').map(e => Number(e)).reduce((a, b) => a - b);
Try to eval! it's safe here
eval("-1000-500-75-33").toString()
console.log(eval("-1000-500-75-33").toString());
And about type casting: After parsing -1000, which is obviously "negative 1000", It will escape casting as soon as it detect a symbol common between numbers & strings. So parseInt is seeing "-1000-500-75-33" as "-1000NotConvertableString", So left the remaining away, returning -1000 as the result of type-casting.
Since they are in a string, ParseInt does not parse the whole string, just finds the first applicable number from the start & returns it. If the start of the string cannot be parsed, it returns NaN
parseInt("-1000NOT_NUMBER") = -1000
parseInt("test-1000`) = NaN
You have to use eval function to do what you want, that evaluates given string as if it were a command entered into the console;
eval("-1000-500-75-33") = -1608

Passing a number to parseFloat() instead of string

In my code, the value of a particular var can originate from any one of a number of different json sources. For some of those sources, the json element concerned will be a string (e.g. "temp": "10.2"), while for other sources the json element will already be a float (e.g. "temp": 10.2).
Does it do any harm (is anything likely to break) if I just pass the json element (from whatever source) through a parseFloat(), even if it's already a float? It seems to work; I'm just thinking about good/bad practice and possible breakage in future or on a different platform.
Thanks.
You should be able to call parseFloat() on a float or a string without any problems. If it is a float already, it's converted to a string first, and then to a float again, so it's a little less efficient, but it shouldn't matter too much.
You should still check the result for NaN, in case there's something unexpected in the data.
The most appropriate method to convert any datatype to a number is to use the Number function:
In a non-constructor context (i.e., without the new operator),
Number can be used to perform a type conversion.
Number("1234") // 1234
Number(1234) // 1234
This method differs from parseFloat in these ways at least:
Number function does not perform "double-conversion" if the input is already a number (ref)
Parse float converts the input to a string then extracts the number (ref)
Number function returns common sense values for most datatypes e.g. Number(true) yields 1
Parse float uses the string value of input so parseFloat(true) tries to parse number from "true" and yields NaN
Number function fails when input string is an invalid number e.g. Number("123abc") yields NaN
Parse float tries to parse as much of a number as possible e.g. parseFloat("123abc") yields 123
If you are sure the value is always a valid number, you should use Number(stringOrNumber).
If you need some additional safety using parseFloat() you could also write your own function which is also performance optimized:
function toFloat(value) {
return typeof value === 'number' ? value : parseFloat(value);
}
I also created a jsPerf test case that shows the performance is >30% better than the plain parseFloat() for a 1:1 ratio between strings and numbers as input values.
Nope there is no problem with passing a number to it
MDN says as long as it can be converted to a number, nothing breaking should happen.
If the first character cannot be converted to a number, parseFloat returns NaN.
As an alternative, you could use the unary operator + which does basically the same thing as parseFloat and also returns NaN if it didn't work.
For instance:
var myFloat = +('10.5');
var myOtherFloat = parseFloat('10.5', 10);
var alreadyAFloat = parseFloat(10.5, 10);
console.log(myFloat === myOtherFloat && myOtherFloat === alreadyAFloat); // true
Wether it's a float or a String using parseFloat() is much safer to avoid all kind of errors.
As you said it will always work, but if you enforce it to be a float you will avoid getting any Exception.
For Example:
Both parseFloat('10.2', 10) and parseFloat(10.2, 10) will work
perfectly and will give you the same result which is 10.2.
Personally I can't see this being a problem what so ever, to be honest I would always use the parsefloat() for one reason, and that is safety. You can never be to sure what may happen, so always predict the worse :D

Javascript convert string to integer

I am just dipping my toe into the confusing world of javascript, more out of necessity than desire and I have come across a problem of adding two integers.
1,700.00 + 500.00
returns 1,700.00500.00
So after some research I see that 1,700.00 is being treated as a string and that I need to convert it.
The most relevant pages I read to resolve this were this question and this page. However when I use
parseInt(string, radix)
it returns 1. Am I using the wrong function or the an incorrect radix (being honest I can't get my head around how I decide which radix to use).
var a="1,700.00";
var b=500.00;
parseInt(a, 10);
Basic Answer
The reason parseInt is not working is because of the comma. You could remove the comma using a regex such as:
var num = '1,700.00';
num = num.replace(/\,/g,'');
This will return a string with a number in it. Now you can parseInt. If you do not choose a radix it will default to 10 which was the correct value to use here.
num = parseInt(num);
Do this for each of your string numbers before adding them and everything should work.
More information
How the replace works:
More information on replace at mdn:
`/` - start
`\,` - escaped comma
`/` - end
`g` - search globally
The global search will look for all matches (it would stop after the first match without this)
'' replace the matched sections with an empty string, essentially deleting them.
Regular Expressions
A great tool to test regular expressions: Rubular and more info about them at mdn
If you are looking for a good tutorial here is one.
ParseInt and Rounding, parseFloat
parseInt always rounds to the nearest integer. If you need decimal places there are a couple of tricks you can use. Here is my favorite:
2 places: `num = parseInt(num * 100) / 100;`
3 places: `num = parseInt(num * 1000) / 1000;`
For more information on parseInt look at mdn.
parseFloat could also be used if you do not want rounding. I assumed you did as the title was convert to an integer. A good example of this was written by #fr0zenFry below. He pointed out that parseFloat also does not take a radix so it is always in base10. For more info see mdn.
Try using replace() to replace a , with nothing and then parseFloat() to get the number as float. From the variables in OP, it appears that there may be fractional numbers too, so, parseInt() may not work well in such cases(digits after decimal will be stripped off).
Use regex inside replace() to get rid of each appearance of ,.
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = a+b;
This should give you correct result even if your number is fractional like 1,700.55.
If I go by the title of your question, you need an integer. For this you can use parseInt(string, radix). It works without a radix but it is always a good idea to specify this because you never know how browsers may behave(for example, see comment #Royi Namir). This function will round off the string to nearest integer value.
var a = parseInt('1,700.00'.replace(/,/g, ''), 10); //radix 10 will return base10 value
var b = parseInt('500.00'.replace(/,/g, ''), 10);
var sum = a+b;
Note that a radix is not required in parseFloat(), it will always return a decimal/base10 value. Also, it will it will strip off any extra zeroes at the end after decimal point(ex: 17500.50 becomes 17500.5 and 17500.00 becomes 17500). If you need to get 2 decimal places always, append another function toFixed(decimal places).
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = (a+b).toFixed(2); //change argument in toFixed() as you need
// 2200.00
Another alternative to this was given by #EpiphanyMachine which will need you to multiply and then later divide every value by 100. This may become a problem if you want to change decimal places in future, you will have to change multiplication/division factor for every variable. With toFixed(), you just change the argument. But remember that toFixed() changes the number back to string unlike #EpiphanyMachine solution. So you will be your own judge.
try this :
parseFloat(a.replace(/,/g, ''));
it will work also on : 1,800,300.33
Example :
parseFloat('1,700,800.010'.replace(/,/g, '')) //1700800.01
Javascript doesn't understand that comma. Remove it like this:
a.replace(',', '')
Once you've gotten rid of the comma, the string should be parsed with no problem.

Why is the result of my calculation undefined?

when I run the javascript code below, I get the variable original as ending as
"1059823647undefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefined0"
why is this happening and how can i fix it?
original="012345678901234567890";
document.write("<textarea>");
document.write(original);
document.write("</textarea>"+"<br>");
/* scramble */
var scramble='1059823647';
scramble=scramble.split('');
var scrambled=new Array();
original=original.split('');
for(i=0;i<original.length;i++){
if(Math.round(Math.round(Math.floor(i/10)*10)+10)>=original.length){
scrambled[i]=original[i];
}else{
scrambled[i]=original[Math.round(Math.round(Math.floor(i/10)*10)+scramble[i%10])];
}
}
original='';
for(i=0;i<scrambled.length;i++){
original+=scrambled[i];
}
document.write("<textarea>");
document.write(original);
document.write("</textarea>"+"<br>");
undefined is being printed because your equation:
Math.round(Math.round(Math.floor(i/10)*10)+scramble[i%10])
is returning a number outside of the range of your array "original"
eg when i = 10, your equation returns 101.
I'm not entirely sure but i think what you mean to do is this:
(Math.floor(i/10)*10) + Number(scramble[i%10])
You're working with strings. But treating them like numbers. JavaScript will convert a string representation of a number to an actual number, but only when it needs to... And the + operator doesn't require such a conversion, as it acts as the concatenation operator for strings.
Therefore, this expression:
Math.round(Math.floor(i/10)*10)+scramble[i%10]
...is converting the first operand into a string and appending an element from the scramble array. You don't notice this for the first ten iterations, since when i<10 the first expression evaluates to 0... But after that, you're suddenly prefixing each scramble element with "10", and trying to access original indexes >= 100... of which there are none defined.
Solution:
Convert your strings to numbers before using them.
Math.round(Math.floor(i/10)*10)+ Number(scramble[i%10])

Categories

Resources