Javascript Regex for decimals [duplicate] - javascript

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

Related

Extracting float number from string using javascript [duplicate]

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());

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);

regex matching decimals in an amount [duplicate]

This question already has answers here:
Regex that matches numeric with up to 2 decimal places
(8 answers)
Closed 9 years ago.
I am new to regex and need to write a regex to match both "100" and "100.00" in an amount value. The last two digits are matched only if these are following a "."
I have tried : ^\d+?(?=([.]{1})\d{2})$ - without any luck
Help is much appreciated
You don't need a lookahead here. You can use an optional non-capture group
^\d+(?:\.\d{2})?$
Use this regex: /^\d+(?:\.\d{2})?$/
Variation on previous answers
^\d{1,8}([\.,]\d{1,2})?$
I've found that users will still enter money values as 1.5 when they mean 1.50, so we use a regex to allow for that as well.
The number of decimal places can be adjusted, as can the number of digits before the decimal point

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