Convert String to Integer in JavaScript - javascript

I have a string value of 41,123 and I want to convert it to an integer in JavaScript.
I tried parseInt(41,123, 10) and parseFloat, but nothing gives me correct answer.
ParseInt, parseFloat work well until comma is encountered, but to above the result is '41'.
Does anyone have an idea about the fix?

var myInt = parseInt("41,123,10".replace(/,/g,""));

Here is the solution:
Number(s.replace(/,/g, ""))
Regex is needed in replacement to remove all comma characters, otherwise only one comma will be replaced.

You can remove the comma, and then parse; let's say the number is variable s:
parseInt(s.replace(/,/g, '')

Related

How to parse number with points and commas

I recieve an string like;
1.234.567,89
I want 1234567.89
Comma is decimal delimiter.Point is thousands, and millions delimiter
I want to treat as a number.
I try replaces, but only works with first ".". And parseFloat.
Also I try some regex that found here,but doesn't work for me
I want this;
var numberAsString= '1.234.567,89';
//Step to clean string and conver to a number to compare (numberAsString => numberCleaned)
if (numberCleaned> 1000000) {alert("greater than 1 million");}
Any Idea?
(Sorry if its a newbie question, but I dont found any solution in hours...)
You can use replace with g
const val = '1.234.567,89'.replace(/\./gi, '').replace(/,/, '.');
console.log(val)
console.log(typeof parseFloat(val))
this should work for the current scenario.
1st remove the dots then replace the comma with dot.
let number = "1.234.567,89";
function parseNum(num){
return num.replace(/\./g, '').replace(",", ".")
}
console.log(parseNum(number));

JavaScript conversion from String with "," to Int

How to convert 1,000 to 1000 using JavaScript.
console.log(parseInt(1,000));
is taking it as 1
You should replace the "," and then doo the parseInt
parseInt("1,000".replace(/,/g,""));
You need to replace comma with empty character. Something like this below:
parseInt("1,000".replace(/,/g, ""))
Try this,
var num = parseInt("1,000".replace(/\,/g, ''), 10);
As, we need to remove "comma" from the string.
We also need "10" as radix as the second parameter.
Thanks
You can use a regular expression to replace all non-digits except for - and . when passing the argument to parseInt:
function parseMyInt(str) {
return parseInt(str.replace(/[^-\.\d]/g,''));
}
console.log(parseMyInt("1,000"));
console.log(parseMyInt("1,000,000"));
console.log(parseMyInt("1,000.1234"));
console.log(parseMyInt("-1,000"));
Edit
Expanded the regex to account for negative numbers and decimals.

`parseInt` is not working as expected when special characters exists

i have var value="10+10" when i try to convert this using parseInt(value) to an int it is giving me NaN. Is their any option to convert a string if it has special characters in it?
The Result shoud be 20 or simply 10+10
you can use eval to evaluate string operations.
since parseInt doesn't recognize characters like + it will return the numbers until special characters.
as a example
(parseInt("10+10") print 10 and
(parseInt("100+10") print 100 and
console.log(parseInt("10+10"))
console.log(parseInt("100+10"))
console.log(eval("10+10"))
console.log(eval("10*10"))

parseInt on (class=) "h310" renders NaN

I've an element like so
<span class='h310'>blah</span>
Now
console.log($(this).attr('class'));
renders
"h310"
but
console.log(parseInt($(this).attr('class')));
renders NaN instead of the very much needed 310.
What am I missing here and how to solve this?
UPDATE
The h is indeed static, I merely added it because "310" is not a valid class name according to the HTML spec while "h310" is.
The h is static
In that case you can simply replace the "h" and convert the string to a number using the unary plus:
+$(this).attr('class').replace('h', '');
> 310
JSFiddle demo.
You need to extract the number part of the string first. parseInt will only extract it automatically if there is no non-numeric character at the beginning of the string
var numberpart = $(this).attr('class').substring(1);
console.log(parseInt(numberpart, 10)); // make sure to provide the radix 10 for decimal numbers
parseInt method will not work here as the class contains the character "h".
Try this (with "h" is static)
<span id="sp1" class='h310'>blah</span>
$(document).ready(function(){
alert($('#sp1').attr('class'));
alert(parseInt($('#sp1').attr('class').replace('h', ''),10));
});
For a general solutions use regex.
console.log(parseInt($('#sp1').attr('class').match(/\d+/),10));
Live DEMO
Yes, obviously it returns NaN as parseInt method won't work for last number from string but if you have 310h then it could be parsed with parseInt:
So, use regular expression here:
console.log(parseInt($('span').attr('class').match(/\d+/),10));
working fiddle
As #James you can also use like this:
$(this).attr('class').replace(/[a-zA-Z ]/g, '');
Try this
var str= $('span').attr('class');
var thenum = str.replace( /^\D+/g, '');
console.log(thenum)
DEMO

What is the most efficient way to filter numbers and parentheses in JavaScript?

I want to filter the number and parentheses out of the following string:
firstText secondText probablyMoreTextToComeWithSpacesBetweenThem (0000)
I want the output to be:
firstText secondText probablyMoreTextToComeWithSpacesAndNumbersBetweenThem
What is the fastest and most efficient way to do this in JavaScript? Thanks.
UPDATE: I want only the numbers between the parentheses to go away and not any other number.
Based on your input, this regex could work:
return input.replace(/\s*\(\d+\)/g, "");
It replaces all parenthesized integers, including all whitespaces before, with an empty string. To remove just all brackets and digits from your string, use
return input.replace(/[()\d]/g, "");
Use replace()
var s = "firstText secondText probablyMoreTextToComeWithSpacesBetweenThem (0000)";
s = s.replace(/\(\d*\)/g, "");

Categories

Resources