Reputation: 429
i just encounter 1 problem on the parseInt i do apply this parseInt for all my project but today i just encounter this
i have a normal text input <input type='text' name='KG'>
and i using jquery to retrieve the input value, then write into another input
<input type='text' name='KG2'>
below are my jquery code
$(":input[name='KG']").keyup(calc);
function calc(){
var kg = $(":input[name='KG']").val();
kg=parseInt(kg);
$(":input[name='KG2']").val(kg);
}
guess what, this the result i get
input@KG > show@KG2
28 > 28
028 > 2
34 > 34
034 > 28
9 > 9
09 > 0
anyone know what went wrong? it can be solve by using Math.round.
Upvotes: 2
Views: 110
Reputation: 707198
Change your code to;
kg=parseInt(kg, 10);
You have to pass the radix (2nd argument) to parseInt()
or it will guess based on the content. The "guess" logic is all described here on MDN.
In your case, if the string starts with a 0
and not a 0x
, it will assume the string is octal which only respects 0-8 as legal characters and converts in base 8.
Moral of the story - ALWAYS pass the radix value to parseInt()
.
Upvotes: 2
Reputation: 324620
028
, 034
and 09
are being treated as octal numbers because they start with 0
and you didn't specify a base. 8
and 9
are invalid digits, so you get 2
and 0
for the first and last, and the second one is converted to decimal 3*8 + 4 = 28
.
Use parseInt(kg,10);
Upvotes: 5
Reputation: 3959
You forgot the second parameter which specifies which base to interpret the int in. To fix your example, try this:
$(":input[name='KG']").keyup(calc);
function calc(){
var kg = $(":input[name='KG']").val();
kg=parseInt(kg, 10);
$(":input[name='KG2']").val(kg);
}
Upvotes: 2