How to remove string after fixed character - javascript

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;

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.

Javascript to cut same second character on a text

For example I have text:
var x="default_1305, default_1695, default_1805";
I want to cut before the second comma to get this text:"default_1305, default_1695".
How can I do this?
var x="default_1305, default_1695, default_1805";
string can be split by , like below:
var res = x.split(",", 2);
Note 2 here in the second param.
And if needed as string, then
var res_string = res.join(",");
Edit:
.split() on MDN
Syntax
str.split([separator[, limit]])
Parameters
separator
Optional. Specifies the character(s) to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.
limit
Optional. Integer specifying a limit on the number of splits to be found. The split() method still splits on every match of separator, until the number of split items match the limit or the string falls short of separator.
Convert string to array and get first two elements
var x="default_1305, default_1695, default_1805";
var b = x.split(',')
var c = b[0]+","+b[1]
You can also use .slice() to get the parts you need, eg:
// added an extra item to distinguish first-two vs all-but-last
var x="default_1305, default_1695, default_1805, default_1962";
// get first two
var result = x.split(",").slice(0,2).join(",");
console.log(result);
// get all but last
var result = x.split(",").slice(0,-1).join(",");
console.log(result);

Javascript How to get first three characters of a string

This may duplicate with previous topics but I can't find what I really need.
I want to get a first three characters of a string. For example:
var str = '012123';
console.info(str.substring(0,3)); //012
I want the output of this string '012' but I don't want to use subString or something similar to it because I need to use the original string for appending more characters '45'. With substring it will output 01245 but what I need is 01212345.
var str = '012123';
var strFirstThree = str.substring(0,3);
console.log(str); //shows '012123'
console.log(strFirstThree); // shows '012'
Now you have access to both.
slice(begin, end) works on strings, as well as arrays. It returns a string representing the substring of the original string, from begin to end (end not included) where begin and end represent the index of characters in that string.
const string = "0123456789";
console.log(string.slice(0, 2)); // "01"
console.log(string.slice(0, 8)); // "01234567"
console.log(string.slice(3, 7)); // "3456"
See also:
What is the difference between String.slice and String.substring?

Extract Fractional Number From String

I have a string that looks something like this
Hey this is my 1.20 string
I'm trying to just extract 1.20 from it.
What's the best way to do this?
I've tried something like this, but I get the value of 1.20,20 rather than just 1.20
var query = $(".query_time").html();
var matches = query.match(/\d.(\d+)/);
The result of the match function is an array, not a string. So simply take
var nb = query.match(/\d.(\d+)/)[0];
BTW, you should also escape the dot if you want to have more precise match :
var nb = query.match(/\d\.(\d+)/)[0];
or this if you want to accept commas (depends on the language) :
var nb = query.match(/\d[\.,](\d+)/)[0];
But the exact regex will be based on your exact needs, of course and to match any number (scientific notation ?) I'd suggest to have a look at more complex regex.
The value of matches is actually [ "1.20", "20" ] (which is an array). If you print it, it will get converted to a string, hence the 1.20,20.
String.match returns null or an array of matches where the first index is the fully matched part and then whichever parts you wanted. So the value you want is matches[0].
Try the following
var nb = query.match(/\d\.\d+/)[0]; // "1.20"
You need to escape . because that stands for any character.
Remove the capture group (\d+) and the second match is not returned
Add [0] index to retrieve the match

Categories

Resources