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
Related
This question already has answers here:
Javascript parse float is ignoring the decimals after my comma
(10 answers)
Closed 7 years ago.
Ok so I'm having a bit of trouble returning a number from an html tag using jquery.
So lets say i have this: <p class="number">4,500.50</p> and i want to get the number from this tag using jquery, so I have the following.
var number = parseFloat($('.number').html());
But this only returns the number 4 instead of the full number. I also treied with the .text() method but the result is the same. Any ideas as to how to resolve this? Any help is appreciated.
Example jsfiddle: https://jsfiddle.net/zf1ctums/1/
Your input string has a non standard (well probably in certain contries people are used to it) format. parseFloat only knows about digits and decimal POINT. So you need to delete the commas:
var number = parseFloat($('.number').html().replace(',', ''));
The problem is that the number should be 4500,50.
You should not pass the thousand separator.
Take a look here.
This question already has answers here:
How to convert a currency string to a double with Javascript?
(23 answers)
Closed 7 years ago.
What I'm talking about is reading a string into a Number, e.g.
"$107,140,946" ---> 107140946
"$9.99" ---> 9.99
Is there a better way than
dolstr.replace('$','');
dolstr.replace(',','');
var num = parseInt(dolstr,10);
???
Using regex is much simpler to read and maintain
parseFloat(dolstr.replace(/\$|,/g, ""));
You can just put all of this in oneliner:
parseFloat(dolstr.replace('$','').split(",").join(""))
Notice that I do not replace the second one, because this will remove just the first ','.
Using a simple regex and the string's replace function
parseFloat(dolstr.replace(/[^\d\.]/g, ''))
Breakdown
It replaces every instance of a character that is not a digit (0 - 9) and not a period. Note that the period must be escaped with a backwards slash.
You then need to wrap the function in parseFloat to convert from a string to a float.
Assuming input is always correct, just keep only digits (\d) and the dot (\.) and get rid of other characters. Then run parseFloat on the result.
parseFloat(dolstr.replace(/[^\d\.]/g, ''))
This question already has answers here:
Javascript concatenating numbers, not adding up
(3 answers)
Closed 7 years ago.
var tt = gas+0.1
document.write (vartt);
Duplicate
You could make use of Number function too.
var tt = Number(gas) + 0.1;
document.write(tt);
The user entered a string. If you want to do arithmetic with it instead of string concatenation, you must convert to a number. There are many different ways to do that including parseInt(gas, 10), parseFloat(gas), Number(gas) and +gas:
Here's one implementation:
var tt = parseFloat(gas) + 0.1;
document.write(tt);
Also, your document.write() statement was not correct either. The variable name is just tt, not vartt.
Unless you are using <input type="number" /> for the input, the user provided data will be a string. By default, when you try to add a string + a number it will cast that number to a string. You can do what Видул Петров suggested and add the unary + to gas to force cast it to a number, however if it's still a string that can't be cast to a number (like someone entering in the word 'five' vs '5'), youll get NaN as a result unless you have the proper control over the incoming data.
This question already has answers here:
Unexpected output in javascript
(5 answers)
Closed 8 years ago.
var apples = prompt('Please enter no. of apples');
var oranges = prompt('Please enter no. of oranges');
var fruits = apples + oranges;
document.write(fruits);
Why does it work with - and * and not +?
Thanks!
You're adding two strings together to get another string. That's how JavaScript does it.
Maybe what you want is numbers:
var fruits = parseInt(apples, 10) + parseInt(oranges, 10);
As a note, using prompt to collect information is utterly barbaric. What you need to do is have two input boxes and a submit trigger that does the math, or since it's so trivial, hook it up to trigger on any change to either value. jQuery basics here.
You're doing string concatenation with the + instead of an addition.
Parse to float or int.
var fruits = parseFloat(apples) + parseFloat(oranages);
prompt returns a string, thus it's appending the strings together.
Javascript will convert to an int when you try other operators on the variables.
Use parseInt to make sure they're ints.
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