Extracting float number from string using javascript [duplicate] - javascript

This question already has answers here:
how to extract floating numbers from strings in javascript
(3 answers)
Closed 6 years ago.
I have a string in javascript:
ECTS: 7.5 pts
From this string I need to extract 7.5 and parse it to a float value..
I've tried searching, but none of the solutions I found did the trick. I've tried:
var regex = /^\d+\.\d{0,3}$/;
var string = "ECTS: 7.5 pts";
var number = parseFloat(string.match(regex));
console.log("number is: " + number);
I've tried with a couple of different regular expressions, but none of them have done the trick.
I've created this fiddle to illustrate the problem.
EDIT1
I used to have this /\d+/ as my regex, but that didn't include floating point numbers.
EDIT2
I ended up using this as my regex /[+-]?\d+(\.\d+)?/g
Updated fiddle

This works nicely, no need for regex:
var s = "ECTS: 7.5 pts";
var n = parseFloat(s.split(" ")[1]);
$("#test").text(n);

did you try this?
var digits = Number((/(\d+\.\d+)/.exec('ECTS: 7.5 pts') || []).pop());

Related

how to evaluate this Number("2/4") in JavaScript [duplicate]

This question already has answers here:
Evaluating a string as a mathematical expression in JavaScript
(26 answers)
Closed 7 years ago.
Hey guys i want to extract/evaluate the answer 2/4 in a string even ehen doing Number ("2/4") it gives me NaN as a result which is fairly reasonable! So my question is how can i evaluate this fraction from a string?
You can do eval("2/4"), which will properly result in 0.5.
However, using eval is a really bad idea...
If you always have a fraction in format A/B, you can split it up and compute:
var s = "11/47";
var ssplit = s.split('/');
document.body.innerText = ssplit[0] / ssplit[1];
Note that Division operator / will implicitly cast strings "11" and "47" to 11 and 47 Numbers.
You are looking for eval. Note
parseFloat("2/4")
2
parseFloat("4/2")
4
eval("4/2")
2
eval("2/4")
0.5
function myFunction() {
var str = "3/4";
var res = str.split("/");
alert(parseFloat(res[0]/res[1]));
}
Try with eval function :
eval("2/4");
Parsing the string only valid for numbers like 0-10 and a decimal (.) and all other if included will then result in NaN.
So, what you can do is like this:
Number(2/4)//0.5
parseFloat(2/4)//0.5
Number('2')/Number('4');//0.5
parseFloat('2')/parseFloat('4');//0.5
Number('2/4');//NaN as / is not parsable string for number
parseFloat('2/4');//2 as upto valid parsable string
parseFloat('1234/4');//1234
So, you can split string then use that like #Yeldar Kurmangaliyev answered for you.
(function(str){
var numbers = str.split("/").map(Number);
return numbers[0] / numbers[1];
})("2/4")
Keep in mind this does not check for invalid input.

(Js) number method to add a comma after the first number and remove the 2 number after comma ?? is there any? [duplicate]

This question already has answers here:
How to round to at most 2 decimal places, if necessary
(91 answers)
Closed 8 years ago.
I want to format a number to two decimal places. Say the user enters 8764444 it should be formatted as 8.76. is there some built-in function in javascript to do that?
No, there is no built in method for exactly that, but you can use the substr method to get parts of a string to do the formatting:
var input = "8764444";
input = input.substr(0, 1) + '.' + input.substr(1, 2);
// show result in Stackoverflow snippet
document.write(input);

toString(16) with leading zeroes [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 9 years ago.
When you convert a small number to a hexadecimal representation, you need leading zeroes, because toString(16) will return f for 15, instead of 00000f. Usually I will use the loop like this:
var s = X.toString(16); while (s.length < 6) s = '0' + s
is there a better way in JavaScript?
UPD: The answer suggested answer How can I create a Zerofilled value using JavaScript? is not what I am looking for, I look for a very short code, that is suited specifically for 24 bit integers converted to a hexadecimal looking strings.
How about
('00000'+(15).toString(16)).substr(-5)
Maybe this:
var s = X.toString(16);
s = "000000".substr(0, 6 - s.length) + s;

Javascript Regex for decimals [duplicate]

This question already has answers here:
Simple regular expression for a decimal with a precision of 2
(17 answers)
Closed 9 years ago.
In Javascript, I am trying to validate a user input to be only valid decimals
I have the following JSFiddle that shows the regex I currently have
http://jsfiddle.net/FCHwx/
var regex = /^[0-9]+$/i;
var key = '500.00';
if (key.match(regex) != null) {
alert('legal');
}
else {
alert('illegal');
}
This works fine for integers. I need to also allow decimal numbers (i.e. up to 2 decimal places)
I have tried many of the regex's that can be found on stackoverflow
e.g.
Simple regular expression for a decimal with a precision of 2
but none of them work for this use case
What am I doing wrong?
This should be work
var regex = /^\d+(\.\d{1,2})?$/i;
Have you tried this?
var regex = /^[0-9]+\.[0-9]{0,2}$/i;
I recommend you to not use REGEX for this, but use a simple !isNaN:
console.log(!isNaN('20.13')); // true
console.log(!isNaN('20')); // true
console.log(!isNaN('20kb')); // false
Try this:
\d+(\.\d{1,2})?
d is for digit
d{1,2} is for 1 digit before . and at least 2 digits such as 0.51

Numeric Values only [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Numeric validation with RegExp to prevent invalid user input
I am new to regex.
Please help writing pattern for numeric values only (for JavaScript).
numeric values only.
allowed decimal "."
no commas.
Thanks!
Here is a great resource for playing around with various regular expressions in JavaScript. Your particular expression looks like this:
/^[-+]?[0-9]+(\.[0-9]+)?$/
Use this regular expression:
^\d+(\.\d+)?$
Rather than using a RegEx and taking care of all permutations of a float number, I would suggest following code to check if it is a valid float number:
var s = ".45";
var d = parseFloat(s);
if (!isNaN(d))
alert("valid float: " + d);
If you have to have a regex then I would suggest:
/^[-+]?(?=.)\d*(?:\.\d+)?$/
Check out the example here for floating point number regex samples...
http://www.regular-expressions.info/floatingpoint.html

Categories