JavaScript conversion from String with "," to Int - javascript

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.

Related

regex replace value only keep numbers and limit decimal places to 2

I have the following text "2345dsds34.000" and i want the following value '234534.00'. I plan to do this via regex replace but somehow it doesnt limit the decimal places to 2.
I am using this "2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, '') but it keeps giving me 234534.000. How can i force it to limit it to 2 decimal points.
console.log("2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, ''))
Thanks
You can use toFixed JS Number function
Number( "2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, '') ).toFixed(2)
You can simply slice the last digit off with .slice(0, -1):
console.log("2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, '').slice(0, -1));
That regex is targetting the characters between some digits and some other digits having a decimal place.
Snapshot from https://regex101.com/
Then, the .replace() method is removing them. That all it does.
Since you don't know how many extra decimal you may have... I suggest you to use parseFloat() and .tofixed(2).
Please have a look at those two documentation links. ;)
var value = parseFloat("2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, '')).toFixed(2);
console.log(value);
You can simply use
[^\d.]
let str = "2345dsds34.000"
let op = parseFloat(str.replace(/[^\d.]+/g, '')).toFixed(2)
console.log(op)
By using a Regex with capturing parentheses It will look like this
var regex = /(\d{4})[a-z]+(\d{2})\.(\d{2}).*/;
var input_chain = "2345dsds34.000";
var output = input_chain.replace(regex, "$1$2.$3");
console.log(output);
Each capturing parentheses can be references in the second part of the replace method by their position number prefixed with a $

How to remove string after fixed character

I have a string like this
str[0] = "99.1234567"
I wnat to remove all charcter after 3 decimal.
Means
str[0] = "99.123"
How to remove this after three decimal. Also sometime i will get only two decimal point like11.36 in that case i wnat to be ignored.
Just find the index of the period, and use substr to get the portion of the string you want.
str[0].substr(0, str[0].indexOf(".")+4);
it's OK if the string is shorter than the length specified in substr.
You can do this using Number.toFixed() , but first you need ot convert the string to number :
var str = "99.1234567"
console.log(Number(str).toFixed(3))
One way to do it :
parseFloat("99.1234567").toFixed(3) // "99.123"
If string :
str[0] = "99.1234567";
parseFloat(str[0]).toFixed(3);
console.log(str[0]); //"99.123"
Or
Math.round(str[0] * 1000)/1000;

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

How can I convert a string(1,234) into a number(1234) using script?

There are several ways to convert a string into an integer, when the string ex:"1,234",
parseInt("1,234")
is converted into number the o/p : will be 1. Is there any way to get the number as 1234 when i enter string "1,234". Please suggest me to get the number. Thanks in advance.
I would strip out all commas from the given string.
parseInt("1,234".replace(/,/g,""),10);
Note that the /,/g is required (as opposed to "," since
"1,234,567".replace(",","") == "1234,567";
"1,234,567".replace(/,/g,"") == "1234567";
Note that "," will only replace the first instance of , while /,/g will replace all instances.
with variable
var tempnum="1,234";
parseInt(tempnum.replace(/,/g,""));
without variable
parseInt("1,234".replace(/,/g,""));
reference replace
check this out
var num = '1,234';
num = num.replace(/,/g, '');
num = parseInt(num, 10);

Convert String to Integer in 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, '')

Categories

Resources