I am stuck in a solution in which I am trying to convert the string to integer, but it truncates the zeroes after comma.Any help on this is much appreciated.
For example,
parseInt("3,50,000") // 3 ==> what i actually need is 3,50,00 of integer type
console.log(parseInt("3,50,000".split(',').join('')))
This:
console.log(parseInt("3,50,000".replace(/,/ig, ''), 10));
Displays:
350000
You must remove commas used for thousands (, millions...) markers (here I replace with empty strings) before parsing an int from a string.
Also, always include the radix, here 10 meaning parse as a base 10 integer.
I used a regular expression to perform the replacement because it is quite efficient, having to process the string only once.
Related
I'm new to programming, and currently I learn JS. There's one thing about operators/type conversions that kind of confused me. Here are some practice examples that I tried:
"4px" - 2
//this returns NaN because this string can't be converted into number to do the arithmetic.
"2" * "3"
// this returns 6 because they can be converted into numbers.
" \t \n" - 2
// now this one is the one that I don't get it. The result is 2. I thought this string can't be converted.
Please enlighten me on the last example, thanks!
Strings that consist of all whitespace characters are converted to the number 0. It's section 7.1.3.1 in the spec. A numeric literal can include leading or trailing spaces plus zero or more digits. If there are no digits, the value is 0.
parseInt(1e1); //10
parseInt('1e1'); //1
parserFloat('1e1') //10
Why parseInt returns 1 in the second case? The three shouldn't return the same result?
1e1 is a number literal that evaluates to 10; parseInt() sees 10 and happily returns that.
'1e1' is a string, and parseInt() does not recognize exponential notation, so it stops at the first letter.
'1e1' as a string is perfectly fine when parsed as a float.
Bonus: parseInt('1e1', 16) returns 481, parsing it as a 3-digit hex number.
When you're trying to parse a string, only the first number in a string is returned. Check function specification at http://www.w3schools.com/jsref/jsref_parseint.asp
Also, you can test it out yourself:
parseInt('2e1') - returns 2
parseInt('3e2') - returns 3
To understand the difference we have to read ecma official documentation for parseInt and parseFloat
... parseInt may interpret only a leading portion of string as an integer value; it ignores any characters that cannot be interpreted as part of the notation of an integer, and no indication is given that any such characters were ignored...
... parseFloat may interpret only a leading portion of string as a Number value; it ignores any characters that cannot be interpreted as part of the notation of an decimal literal, and no indication is given that any such characters were ignored...
parseInt expects ONLY an integer value (1, 10, 28 and etc), but parseFloat expects Number. So, string "1e1" will be automatically converted to Number in parseFloat.
parseInt('1e1'); // 1
parseFloat('1e1'); // 10
I know that to convert a C# date, like /Date(1430341152570)/ to a JavaScript date, it's the following:
var part = "/Date(1430341152570)/".substr(6); // => "1430341152570)/"
var jsDate = new Date(parseInt(part));
My question: how is the part value, which includes a trailing )/ able to be parsed into an int via parseInt? Wouldn't JS throw an error on trying to convert something that has the )/ characters? It would make more sense to me if the part value was something like "/Date(......)/".substr(6).replace(')/','') b/c at least you're making it a string of #'s to be parsed to an int.
From the Mozilla documentation:
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. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.
) isn't a numeral, so everything from there onwards is ignored as specified.
Or from the ES6 draft standard:
parseInt may interpret only a leading portion of string as an integer value; it ignores any code units that cannot be interpreted as part of the notation of an integer, and no indication is given that any such code units were ignored.
I have a button where in the code behind I add a onclick and I pass a unique ID which will be passed to the js function. The id starts with a 0.
It wasn't working and eventually I figured out that the number, id, it was passing was wrong...
Ie. see this: js fiddle
It works with a ' at the start and end of the number. Just wondering why 013 turns to 11. I did some googling and couldn't find anything...
Cheers
Robin
Edit:
Thanks guys. Yep understand now.
As in this case the 0 at the start has a meaning, here the recipient ID in a mailing list, I will use '013' instead of just 013, i.e. a string. I can then split the values in js as each of the 3 values represents a different id which will always be only 1 character long, i.e. 0-9.
A numeric literal that starts with a 0 is treated as an octal number. So 13 from base 8 is 11 in base 10...
Octal numeric literals have been deprecated, but still work if you are not in strict mode.
(You didn't ask, but) A numeric literal that starts with 0x is treated as hexadecimal.
More info at MDN.
In your demo the parameter is called id, which implies you don't need to do numerical operations on it - if so, just put it in quotes and use it as a string.
If you need to be able to pass a leading zero but still have the number treated as base 10 to do numerical operations on it you can enclose it in quotes to pass it as a string and then convert the string to a number in a way that forces base 10, e.g.:
something('013');
function something(id){
alert(+id); // use unary plus operator to convert
// OR
alert(parseInt(id,10)); // use parseInt() to convert
}
Demo: http://jsfiddle.net/XYa6U/5/
013 is octal, not decimal, it's equal 11 in decimal
You should note that 013 starts with a 0. In Javascript, this causes the number to be considered octal. In general you'll want to use the decimal, and hexadecimal number systems. Occasionally though, octal numbers are useful, as this question shows.
I hope this helps! :)
If the first digit of a number is a zero, parseInt interprets the number as an octal.
You can specify a base of ten like this:
parseInt(numberString, 10)
You could also remove such zeros with a regex like this (the result will be a string):
numberString.replace(/^0+/g, '');
Is there any built in method to get which can parse int from string ("23px")?
I know I can use substring and then parseInt but I want to know if there is any other way available to do this.
parseInt will grab the first set of contiguous numbers:
parseInt('23px');
returns 23.
If there is any chance there will be leading zeros, use a radix:
parseInt('23px', 10);
which is a good habit in general.
parseInt can do it. Just use:
var num = parseInt("23px", 10);
It will parse the integer part and ignore the rest.