JavaScript - Taking Input and displaying it to HTML element, as an integer - javascript

What I am trying to do is make an EV Track for Pokemon, you do not need to know what that is. Basically I want to add, for example, 3 into the attack input box, and 2 into defense and click submit, then 3 should appear in the grid under attack, and 2 under defense. Then if I put 1 in the attack input box, it should add 1 to the display in the grid.
But right now, instead of adding the numbers like numbers, it treats them as strings, and only adds them to the attack display.
Here is my code
http://pastebin.com/xy8232nG
Sorry if I do something wrong related ot the format of my question, just let me know, I'll fix it
So I added that parseint thing, and it works fine until I change the number or add 2 to attack and 2 to hp or something like that, it gives me "NaN" instead of a number
edit: so only the attack and special attack displays work, and if i input a value into any other stat, the special attack and attack values change to "NaN"

First off, you wrote defD as defF in your code by accident.
But more importantly, you are mixing strings and numbers. In Javascript, innerHTML returns a string. A string can be any piece of text, like "I am a jelly donut". It returns a string because innerHTML is capable of carrying more than numbers - it could contain text too. So innerHTML returns a string, just to be safe.
As such, you are trying to add a number to a string (piece of text) and you can't add a number to a sentence. So Javascript decides to treat the number like another piece of text rather than a number, and simply tacks the second number on the end of the first one rather than doing a mathematical equation.
Now many others have been saying "use parseInt, use parseInt!" and normally, that would work. That is because parseInt is a function that takes strings and converts them to numbers. However, when you start out, some of your textboxes are empty, so parseInt does not know what to do. So you get NaN (or, "Not a Number" to be exact) because the box is blank.
Usually, I avoid using parseInt because it is a function and in general, using plain math works faster and better than using a function in JS. An easy workaround to your problem is to to multiply the strings by one. Now, I know what you're thinking. "But if adding a number to text doesn't work, why does multiplying?" Simple. You cannot multiply text. As such, Javascript is forced to think of it like two numbers, rather than two strings.
atk += document.getElementById('atk').value*1;
spa += document.getElementById('spa').value*1;
def += document.getElementById('def').value*1;
spd += document.getElementById('spd').value*1;
hp += document.getElementById('hp').value*1;
spe += document.getElementById('spe').value*1;
document.getElementById("atkD").innerHTML = atk;
document.getElementById("spaD").innerHTML = spa;
document.getElementById("defD").innerHTML = def;
document.getElementById("spdD").innerHTML = spd;
document.getElementById("hpD").innerHTML = hp;
document.getElementById("speD").innerHTML = spe;
An added bonus is that this won't return NaN like parseInt does. Try it in your code and see.
(Note: you might want to use a for loop to loop through those and shorten your code instead. It isn't really necessary, but it would look nicer in your code.)

Use the parseInt function to make the values integers. Example:
.....
atk += parseInt(document.getElementById('atk').value);
.....

Related

problem with parsing numbers using JQuery

i have a Javascript file that calculates and parse the rows in a crm module called jobs.
I have function called recalculateSummary that calculate the price like this
I want it to show 3,578.00 in total like Line Total
The problem is the function parseFloat i think it ignores the ',' as i want if i write 3,578.00 the total should be 3,578.00.
I was able to achive this by removing parseFloat function and removing the ReplaceAll function but i got error when i add more rows the total value becomes 0.00.
recalculateSummary: function(){
var subtotal = 0;
$.each($('.row_line_total'), function(index,value){
lineTotal = $(value).html().replaceAll(',','.').replaceAll(' ','');
subtotal += parseFloat(lineTotal);
});
i know the question isn't clear but i need some help
Are trying to add toFixed(2) for calculation result?
I mean this:
$('.summary_subtotal').html($.number(subtotal,2));
->
$('.summary_subtotal').html($.number(subtotal.toFixed(2),2));
The reason is that by replacing the comma with the dot, parseFloat will interpret that as the decimal separator and so your number suddenly is a factor of 1000 smaller.
Take for example 3,578.00
Your code will grab that value as a string with $(value).html().
This is OK, although it would be better to do $(value).text() as
you are not really interested in HTML encoding, but plain text.
Then the code performs a disastrous replacement with
.replaceAll(",", "."). This will turn the string to "3.578.00"
(Not good!).
Finally the code converts this string to number with parseFloat.
The first dot is interpreted as decimal separator, not as thousands
separator (which it originally was). The second dot cannot be
interpreted as part of the number, and so parseFloat returns a
number with value 3.578. You probably have some other mechanics in
place to only display 2 decimal digits, so this value ends up on the
page as 3.58 (rounded).
In order to fix this problem, replace this:
lineTotal = $(value).html().replaceAll(',','.').replaceAll(' ','');
with:
lineTotal = $(value).text().replace(/[^.\d]/g, '');
Here we remove anything that is neither a dot (.), nor a digit (\d), using a regular expression: [^.\d]. So now the example value will become "3578.00" (the thousands separator is removed). parseFloat will turn this string into the number 3578. Your rendering mechanics will possibly render that with two decimals and a thousand separator as 3,578.00
All in all it is better to write your logic based on numeric variables and only use the DOM elements for output, not to read values from it (which are already formatted).

How to get the number from an input in JavaScript?

I have defined an input in HTML that represents a number. I need to parse the string in JavaScript to a number taking into consideration the different languages that will be entered by the user, for example: '1.34' in English will be written as '1,34' in French. parseFloat('1,344') will be return 1 in case we are in English standard.
You could probably find a library for it, but you can also pretty easily format the numbers into the wanted format yourself.
When you get a number from the input just convert it to string and then use the indexOf() function (http://www.w3schools.com/jsref/jsref_indexof.asp) to see if there's a comma or a dot in the number. It returns the position index of that element in a string so you can then replace with the wanted one to format the number. Position will be -1 if there is no dot/comma.
var num = 32.14;
var string = String(num);
var position = string.indexOf(".");
Hope this helps you.
If it's only those two representations you consider, then another easy solution is to always do
var floatNum = num.replace(/,/g,".");
and then just treat it like any float number.
Unless you really need it for other number systems I'd avoid using a library. Libraries tend to be too big for most projects to utilize properly in my opinion.

Javascript variable not displaying the number assigned to it

I'm writing a javascript program that needs random 10-digit numbers which can sometimes have the 10th digit as 0. I assigned a variable to one of these numbers and then logged it to make sure everything was alright...but it wasn't. Here is my code:
var candidate = 0135740250;
var candidate2 = 0272189318;
console.log(candidate); // Returns 24625320
console.log(candidate2); // Returns 272189318
I tried taking the 0 off the beginning of candidate, and that made it return correctly, but I don't understand why it doesn't work in the first place. I included candidate2 above because whatever I do to it, adding 0s in the middle, changing it in other ways, it stays correct, so I can't figure out why candidate is being screwed up. I vaguely understand the number storage system in Javascript and that its not perfect, but I need a predictable, repeatable way to return the correct number.
The question is: what is happening here and how can I reliably avoid it?
"The question is: what is happening here..."
The first is a valid octal, so it gets converted as such.
The second is not a valid octal because of the 8 and 9, so it gets the base 10 representation with the leading 0 removed since it adds no value.
"...and how can I reliably avoid it?"
Avoiding it will depend on how you're generating your numbers. If you were using .random() it wouldn't be an issue, so I'd assume they're coming from some sort of string representation.
If so, and if you're using parseInt() to get the actual number, then pass it 10 as the second argument to ensure base-10 representation.
JavaScript treats any number beginning with 0 as octal if it is a valid octal.
Another quack is, if you know the length of string to generate
"use strict"
var strlent = 10
console.log(candidate2.toString().length < strlent ? "0" +
candidate2.toString() : candidate2.toString())
>>>0272189318

Javascript parseFloat 10 instead of e

Im using parseFloat on very high numbers or very low numbers.
The return value is like 123*10e15 , I need to be like 123*10^15 . 15 needs to be in upper writing as a pow.
Thanks.
parseFloat turns a string into a number. A number has no "format"; it gets turned back into a string (by Float's method toString) when you display it. If you want to display it with a caret, you will need to format (or reformat) it yourself into a string: easiest like this:
123e45.toString().replace('e', '*10^') // result: "1.23*10^+47"
(if the + bugs you, you can try this, using a regexp:)
123e-45.toString().replace(/e\+?/, '*10^') // result: "1.23*10^47"

why do convert numbers to string in Javascript using tostring method?

I was wondering why do people have to convert numbers to string. What are the practical uses for that kind of conversion?
Similarly why do developers use parseInt or parseFloat to convert a string to a number.
thanks
The variable’s data type is the JavaScript scripting engine’s interpretation of the type of data that variable is currently holding. A string variable holds a string; a number variable holds a number value, and so on. However, unlike many other languages, in JavaScript, the same variable can hold different types of data, all within the same application. This is a concept known by the terms loose typing and dynamic typing, both of which mean that a JavaScript variable can hold different data types at different times depending on context.
With a loosely typed language, you don’t have to declare ahead of time that a variable will be a string or a number or a boolean, as the data type is actually determined while the application is being processed. If you start out with a string variable and then want to use it as a number, that’s perfectly fine, as long as the string actually contains something that resembles a number and not something such as an email address. If you later want to treat it as a string again, that’s fine, too.
The forgiving nature of loose typing can end up generating problems. If you try to add two numbers together, but the JavaScript engine interprets the variable holding one of them as a string data type, you end up with an odd string, rather than the sum you were expecting. Context is everything when it comes to variables and data types with JavaScript.
Using parseInt and parseFloat is important if you want to do arithmetic operations on a number which is in string form. For example
"42" + 1 === "421"
parseInt("42") + 1 === 43;
The reverse is true when you want to do string operations on values which are currently a number.
42 + 1 === 43
(42 + "") + 1 === 421
Why one would want to do the former or latter though is very scenario specific. I'd wager the case of converting strings to numbers for arithmetic operations is the more prominent case though.
An example of when converting numbers to strings is useful is when you want to format the number a certain way, perhaps like a currency (1234.56 -> $1,234.56).
The converse is useful when you want to do arithmetic on strings the represent numbers. Say you have a text box were you allow the user to input a number. The value of that text box will be a string, but you need it as a number to do some arithmetic with it, so you would use parseInt and parseFloat.
string -> number:
Think about simple number validation using JS. if you can convert a string into a number, then you can validate that number before posting to a number, or for use in an arithmetic operation.
number -> string:
String concatenation mainly and display purposes. The language will most often use implicit conversion to convert the number into a string anyway, such as:
1 + " new answer has been posted"
Do remember, Javascript is a loosely typed language. This can hide a lot of implicit type-casting that is occurring.

Categories