jquery javascript set values as float before adding - javascript

My app has a textbox on a webpage whose value is looked up and then added or subtracted to another value.
It seems to subtract well, but when adding, it interprets the value in the textbox as text, and adds on the other float as a text as well:
Here's the source code of the thing changing:
$('#mymoney').val($('#mymoney').val() + $prevevent.close);
//...or when subtracting:...//
$('#mymoney').val($('#mymoney').val() - $prevevent.close);
How to I tell the mymoney to be interpreted as a float instead of a string?

This is because .val() is reading the value as a string and concatinating. You can parse it into a integer with parseInt():
$('#mymoney').val( parseInt($('#mymoney').val()) + $prevevent.close);
For float values use parseFloat():
$('#mymoney').val( parseFloat($('#mymoney').val()) + $prevevent.close);

This is simple by using parseFloat
$('#mymoney').val(parseFloat($('#mymoney').val()) + $prevevent.close);
Because JS will interpretes the other hand to string if either operator hand is a string.
Or, you can use Number() to parse string to (int or float) number like:
$('#mymoney').val(Number($('#mymoney').val()) + $prevevent.close);
But the parseInt or parseFloat is prefer, because it acts more normally than Number. For Example, Number will parse null and "" to 0, and erase the 0 at the beginning of a number although it may represent an octal digit. Additionally, parseInt will return the correct part until it can't be parsed, like: parseInt("15abc") returns 15.

Other answers are correct. However, here is another syntactical spice of magic that will do wonders for integer values.
Instead of using parseInt you can just prepend your expression with a + and it will parse the following value to integer.
$('#mymoney').val( (+$('#mymoney').val()) + $prevevent.close);

Related

How can I remove all decimals from a JavaScript variable?

How can I remove all decimals from a number? I want to get the number as specified below. I need to remove decimal points only. I am not getting the logic for it.
If number x= 1.1.6;
then I want result as 116
and when x=0.0.6;
then I want result as 6.
Since 1.1.6 is not a valid numerical value in JavaScript, I assume that you're starting with a string. You can get the result as an integer value with:
parseInt(number.replace(/\./g, ''))
If desired, you can then turn that back into a string with no leading zeroes with:
'' + parseInt(number.replace(/\./g, ''))
try this. replace all the . using replace method and convert to integer
document.write(parseInt("1.1.6".replace(/\./g, '')))
document.write('<br>')
document.write(parseInt("0.0.6".replace(/\./g, '')))

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

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;

When to use parseInt

Which rule do I have to follow when extracting numbers out of DOM and calcluation with them? How does javascript knows that a value is a number or not? Should I always use parseInt?
Given following Code:
HTML
<div id="myvalue">5</div>
<div id="withParseInt"></div>
<div id="withoutParseInt"></div>
<div id="withoutParseIntButIncrement"></div>
JS & jQuery:
var value = $('#myvalue').text();
$('#withParseInt').text(parseInt(value) + 1);
$('#withoutParseInt').text(value + 1);
$('#withoutParseIntButIncrement').text(value++);
Gives following output:
5
6
51
5
Fiddle: http://jsfiddle.net/ytxKU/3/
The .text() method will always return a string. Some operators, like the + operator, are overloaded to perform both arithmetic and string operations. In the case of strings, it performs concatenation, hence the "51" result.
If you have a string and need to use a non-coercing operator, you will have to use parseInt (or some other method of converting to a number).
However, the * operator for example implicity performs this coercion, so you wouldn't need the parseInt call in that situation (see an updated fiddle for example).
Note that the increment ++ operator does coerce its operand, but you've used the postfix operator so it won't have any effect. Use the prefix operator and you can see it working:
$('#withoutParseIntButIncrement').text(++value);
So, to summarise:
// Parses string to number and adds 1
$('#withParseInt').text(parseInt(value) + 1);
// Coerces number 1 to string "1" and concatenates
$('#withoutParseInt').text(value + 1);
// Implicity coerces string to number, but after it's been inserted into the DOM
$('#withoutParseIntButIncrement').text(value++);
// Implicity coerces string to number, before it's been inserted into the DOM
$('#withoutParseIntButIncrement').text(++value);
// Implicity coerces to number
$('#withoutParseIntButMultiply').text(value * 2);
Side note: it's considered good practice to always pass the second argument (the radix) to parseInt. This ensures the number is parsed in the correct base:
parseInt(value, 10); // For base 10
One and only rule:
Every value that you retrieve from the DOM is a string.
Yes, you should always use parseInt() or Number() to be on the safe side. Otherwise Javascript will decide what to do with it
The value itself is a string
Using operator + will concatenate two strings
Using operator - will calculate the numerical difference
...
It's always good to use parseInt just to be on the safe side, especially as you can supply a second parameter for the numerical system to use.
By the way, in your final example it should be ++value if you want it to equal 6.

How to delete "px" from 245px

Whats a simple way to delete the last two characters of a string?
To convert 245px in 245 just run:
parseInt('245px', 10);
It retains only leading numbers and discards all the rest.
use
var size = parseInt('245px', 10);
where 10 is the radix defining parseInt is parsing to a decimal value
use parseInt but don't use parseInt without a radix
The parseInt() function parses a string and returns an integer.
The signature is parseInt(string, radix)
The second argument forces parseInt to use a base ten numbering system.
The default input type for ParseInt() is decimal (base 10).
If the number begins in "0", it is assumed to be octal (base 8).
If it begins in "0x", it is assumed to be hexadecimal
why? if $(this).attr('num') would be "08" parsInt without a radix would become 0
To convert a pixel value without the "px" at the end. use parseFloat.
parseFloat('245px'); // returns 245
Note: If you use parseInt, the value will be correct if the value is an integer. If the value is a decimal one like 245.50px, then the value will be rounded to 245.
This does exactly what you ask: remove last two chars of a string:
s.substr(0, s.length-2);
Surprisingly, the substring method s.substr(0, s.length-2); is actually quite a bit faster for removing the px (yes it isn't as clean looking, and if there is a space it will remain -- "250px" -> "250" vs "250 px" -> "250 ").
If you want to account for spaces (which you probably should) then using the .trim() function will actually slow down the substr test enough that the parseInt method actually becomes superior.
An added benefit of using parseInt(s, 10) is that you also get a type conversion and can immediately start to apply it to mathematical functions.
So in the end, it really depends on what you plan on doing with the result.
If it is display only, then using the substr method without a trim would probably be your best bet.
If you're just trying to see if the value without px is the same as another value s.substr(0, s.length-2) == 0, then using the substr method would be best, as "250 " == 250 (even with the space) will result as true
If you want to account for the possibility of a space, add it to another value, or to compute something with it, then you may want to consider going with the parseInt route.
http://jsperf.com/remove-px-from-coord
The tests on jspref account for a space. I also tried a s.split('px')[0] and s.replace(/ *px/g, '') function, both found to be slower.
Feel free to add additional test cases.
Although parseInt() is a good option but still it is good to have many other solutions
var pixels = '245px';
Number(pixels.replace('px', ''));
substr() is now a legacy feature; use substring() instead: (syntax is the same in this case)
str.substring(0, str.length-2);
Or, use slice():
str.slice(0, -2);
slice() looks much cleaner, IMO. Negative values count back from the end.
Check http://www.w3schools.com/jsref/jsref_substr.asp
In your case would be something like
string.substr(0, string.length - 2)
I prefer:
"245px".replace(/px/,'')*1
since it's not surrounding the input.
Also, the *1 is for casting it to int.

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