I have string like "17,420 ฿". How to change this as integer value. I have done
var a = "17,420 ฿"
var b = a.split(' ')[0];
console.log(Number(b))
But I am getting NaN because of ,.
So i have done like below
var c = b.replace( /,/g, "" );
console.log(Number(c));
Now, I am getting 17420 as an integer.
But, is there any better method to do it.
You could start by stripping off anything that's NOT a number or a decimal point. string.replace and a bit of RegExp will help. Then use parseFloat or Number to convert that number-like string into a number. Don't convert to an integer (a decimal-less number), since you're dealing with what appears to be currency.
const num = parseFloat(str.replace(/[^0-9.]/g, ''))
But then at the end of the day, you should NOT be doing string-to-number conversion. Store the number as a number, then format it to a string for display, NOT the other way around.
You can easily remove all non-digits with a regex like so:
a.replace(/\D/g, '');
Then use parseInt to get integer value:
parseInt(b);
Combined:
var result = parseInt(a.replace(/\D/g, ''));
You can use parseInt after removing the comma
var a = "17,420 ฿"
console.log(parseInt(a.replace(",",""), 10))
o/p -> 17420
Number(a.replace(/[^0-9.]/g, ""))
This will replace all not numbers chars... is that helpful?
Split for the , and then join via . and then parse it as a float. Use .toFixed() to determine how many decimal places you wish to have.
console.log(
parseFloat("17,420 ฿".split(' ')[0].split(',').join('.')).toFixed(3)
);
As a function:
const convert = (str) => {
return parseFloat(str.split(' ')[0].split(',').join('.')).toFixed(3)
}
console.log(convert("17.1234 $"));
console.log(convert("17 $"));
console.log(convert("17,2345 $"));
Alternative:
const convert = (str) => {
let fixedTo = 0;
const temp = str.split(' ')[0].split(',');
if(temp.length > 1){
fixedTo = temp[1].length;
}
return parseFloat(temp.join('.')).toFixed(fixedTo)
}
console.log(convert("17,1234 $"));
console.log(convert("17,123 $"));
console.log(convert("17,1 $"));
console.log(convert("17 $"));
Related
I'm working with a string "(20)". I need to convert it to an int. I read parseInt is a function which helps me to achieve that, but i don't know how.
Use string slicing and parseInt()
var str = "(20)"
str = str.slice(1, -1) // remove parenthesis
var integer = parseInt(str) // make it an integer
console.log(integer) // 20
One Line version
var integer = parseInt("(20)".slice(1, -1))
The slice method slices the string by the start and end index, start is 1, because that’s the (, end is -1, which means the last one - ), therefore the () will be stripped. Then parseInt() turns it into an integer.
Or use regex so it can work with other cases, credits to #adeithe
var integer = parseInt("(20)".match(/\d+/g))
It will match the digits and make it an integer
Read more:
slicing strings
regex
You can use regex to achieve this
var str = "(20)"
parseInt(str.match(/\d+/g).join())
Easy, use this
var number = parseInt((string).substr(2,3));
You need to extract that number first, you can use the match method and a regex \d wich means "digits". Then you can parse that number
let str = "(20)";
console.log(parseInt(str.match(/\d+/)));
Cleaner version of Hedy's
var str = "(20)";
var str_as_integer = parseInt(str.slice(1, -1))
I'm trying to find out how to get numbers that are in a string.
I tried the Number(string) function but it returns me a "NaN" ...
For example :
let str = "MyString(50)";
/*Function that return "NaN"*/
let numbers = Number(str);
console.log(numbers);
//Output expected : 50
//Output if get : 50
Do anyone has an idea why "Number" isn't returning me the right value or another way to do it ?
Thanks for answers.
You can use String.match with a regex to filter out numbers, and use unary + or Number(str) or parseInt to get the number
let str = "MyString(50)";
let numbers = +str.match(/\d+/);
console.log(numbers);
The match regular expression operation is used to get number.
var str = "MyString(50)";
var matches = str.match(/(\d+)/);
console.log(matches[0]);
Refer this link to know about regular expression link [https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions].
Here a more comprehensive regex to detect all kinds of numbers in a string:
/ 0[bB][01]+ | 0[xX][0-9a-fA-F]+ | [+-]? (?:\d*\.\d+|\d+\.?) (?:[eE][+-]?\d+)? /g;
binary | hex | sign? int/float exponential part?
const matchNumbers = /0[bB][01]+|0[xX][0-9a-fA-F]+|[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g;
let str = `
Let -1
us +2.
start -3.3
and +.4
list -5e-5
some +6e6
number 0x12345
formats 0b10101
`;
console.log("the string", str);
const matches = str.match(matchNumbers);
console.log("the matches", matches);
const numbers = matches.map(Number);
console.log("the numbers", numbers);
.as-console-wrapper{top:0;max-height:100%!important}
I have an string defining the lattitude of an event with this format "p002.155" and "n003.196" being "p" and "n" the form the system define if the number is positive or negative.
I need to parse the string to float, tried with parseFloat but keeps getting NaN value because of the char inside the string
how can I do it?? Thanks.
You can replace the char and then convert to float:
var str = "n002.155";
str = +str.replace("p","").replace("n","-"); //here the leading `+` is casting to number
console.log(str);
You can use substring and look at the first char
function getFloat(str) {
var sign = str.charAt(0)=="n"?-1:1;
return parseFloat(str.substring(1))*sign;
}
var latPStr = "p002.155", latNStr = "n003.196";
console.log(getFloat(latPStr),getFloat(latNStr));
You can convert a string to float like this:
var str = '3.8';
var fl= +(str); //fl is a variable converted to float
console.log( +(str) );
console.log("TYPE OF FL IS THIS "+typeof fl);
+(string) will cast string into float.
In javascript, I am trying to make a program that had to do with fractions that you can input and I need a function that will convert a fraction in this format( "10/27") to either 10 or 27 depending on user specification but I don't know how I would code this function. Any code or suggestions to get me started would be much appreciated.
You can search in string using indexOf(). It returns first position of searched string.
If you want to split string using a character in it, use split(). It will return an array. So for eg: in you string 27/10, indexOf / is 3 but if you do split, you will get array of 2 values, 27 and 10.
function splitString(str, searchStr) {
return str.split(searchStr);
}
function calculateValue(str) {
var searchStr = '/';
var values = splitString(str, searchStr);
var result = parseInt(values[0]) / parseInt(values[1]);
notify(str, result);
}
function notify(str, result) {
console.log(result);
document.getElementById("lblExpression").innerText = str;
document.getElementById("lblResult").innerText = result;
}
(function() {
var str = "27/10";
calculateValue(str)
})()
Expression:
<p id="lblExpression"></p>
Result:
<p id="lblResult"></p>
You can split the string into an array with split(), then take the first or second part as the numerator or denominator:
function getNumerator(fraction) {
// fraction = "10/27"
return fraction.split("/")[0];
}
function getDenominator(fraction) {
// fraction = "10/27"
return fraction.split("/")[1];
}
var fraction = "10/27".split("/");
var numerator = fraction[0];
var denominator = fraction[1];
You can of course use a library for it too: https://github.com/ekg/fraction.js
With this library the answer would be:
(new Fraction(10, 27)).numerator
Considering str contains the input value then,
a = str.substring(str.indexOf("/")+1);
b = str.substring(0, str.indexOf("/"));
Output:
if str is "10/17" then,
a == 17;
b == 10;
I have a string which contains a decimal point e.g. "10.00" and I want to hide it using jQuery? I need to trim it to "10" from "10.00".
Many options, I'd probably go with
var foo = "10.00";
foo.split('.')[ 0 ];
Math.floor(parseInt("10.00",10));
// 10
If you need it back as a string rather than an int,
Math.floor(parseInt("10.00",10)).toString();
// "10"
Edit:
Actually, Math.floor() isn't necessary. parseInt() will do it alone:
parseInt("10.00",10).toString();
// "10"
The following will remove the decimal values by converting it to an integer:
// Returns an int of 10.
var myInteger = parseInt("10.00");
or
// Returns a string of "10".
var myString = parseInt("10.00").toString();
Or the regex way. Since we start with a String and want a String out, why bother converting back and forth to numbers ? And this will be faster than 'split'.
/[^\.]*/.exec("10.00")[0]
Pure string way to do this is
var Trim = function( n ) {
var index = n.indexOf('.');
return n.substring(0, index - 1);
};
//usage
Trim( "10.00" );
The following may be useful:
intvalue = parseInt($('#quantity').val(), 10);