Regular expression for validating decimal numbers - javascript

function validateDecimal(number,maxDigits)
{
eval("var stringvar=/^[-+]?([0-9]*\.[0-9]{0,"+maxDigits+"})|([0-9]+)$/");
return stringvar.test(number);
}
I wrote above function to validate decimal numbers. The variable 'maxDigits' uses to specify the number of digits in fractional part and 'number' as the value to be validated. But it returned 'true' when I tried with a numeric value followed by a character for eg: 24y. Can anyone help me to figure out my mistake.

Without going into the regex, I think the problem in your code is that you should escape the special character twice. Since you're putting it all inside a string, a single backslash is escaped by the string parsing.
I think this should work:
eval("var stringvar=/^[-+]?([0-9]*\\.[0-9]{0,"+maxDigits+"})|([0-9]+)$/");

This regular expression would validate a number with maxDigits of decimals:
^[-+]?[0-9]*.[0-9]{10}$. This will validate it to 10 decimal places.
Implementing that into JavaScript would look like:
eval("var stringvar=^[-+]?[0-9]*.[0-9]{" + maxDigits + "}$");, or thereabouts.

I have just tried this one and it worked for me: ^[+-]?[0-9]*(\.[0-9]{0,5})?$.
In my case I made a minor modification, you seem to be matching either a decimal number or else a whole number. In my case, I modified the regular expression to take a whole number with an optional decimal section.
As is, the regular expression will match values like: .222, 23.22222 but not 4d.22222, 33.333333, etc.
var n1 = "4.33254";
var n2 = "4d.55";
eval("var stringvar=/^[+-]?[0-9]*(\\.[0-9]{0,5})?$/");
alert(stringvar.test(n1));
alert(stringvar.test(n2));
Yielded: true and false respectively.

Related

Regex to match if string contains integer/decimal with digits

I want to write a regex that allows an integer number, or a decimal number with 0 - 2 decimal digits.
Valid Input
1
1.
1.1
1.11
111111111
111111111.
111111111.1
111111111.11
Invalid Input
a
a.
1.a
1.111
1.1111
string allows any number of digit characters, but only allows 1 decimal/period
if a period/decimal exists: only allow 2 digit characters after the decimal
Here is the regex I came up with
\d*\.?([\d]){0,2}
I am having trouble testing it to ensure it works. I found a couple ways of testing it. Using the test method which I just used w3schools setup here. The other way was with some javascript regular expression tester like regexr and regex101. For all of these: it appears that either my regular expression is returning false positives, or my regular expression does not work as intended.
Question: What regex would do what I want it to do?
You need to make sure that you check the complete string (from the first char to the last char) using ^...$
The first digit should appear at least 1 time (so you want to use + and not *).
Check this example:
r = /^\d+\.?\d{0,2}$/
tests = ['1', '1.', '1.1', '1.11', '111111111', '111111111.', '111111111.1', '111111111.11', 'a', 'a.', '1.a', '1.111', '1.1111']
tests.forEach(function(val) {
console.log(val, val.match(r) ? ': valid' : ': invalid');
});
update
Following the comments - if you need a solution for "integer number, or a decimal number with 0 - 2 decimal digits" (like you said in the question, but not like the valid input section), you can use this:
r = /^\d+(\.\d\d{0,1})?$/
console.log('1.'.match(r))
tests = ['1', '1.', '1.1', '1.11', '111111111', '111111111.', '111111111.1', '111111111.11', 'a', 'a.', '1.a', '1.111', '1.1111']
tests.forEach(function(val) {
console.log(val, val.match(r) ? ': valid' : ': invalid');
});
Don't forget closing and opening in Regex, many new Regex for get it and they end up unwanted result, everything should between ^ and $, ^ is starting point of the word(digit) boundary and $ is ending point...something like below should help you, try:
'use strict';
var decimal = /^\d+(\.\d\d{0,2})$/, num = 111111111.11;
console.log(decimal.test(num));
Hope this helps...

Best way to remove thousand separators from string amount using a regex

I have variables that contain amounts and would like to remove the (US) thousand separators but also have to cover the scenario that there may be non-US formatted amounts where the comma is used for the decimals instead of for the thousands where I don't want to replace the comma.
Examples:
1,234,567.00 needs to become 1234567.00
1,234.00 needs to become 1234.00
but
1.234.567,00 needs to remain unchanged as not US format (i.e. comma here is used for decimals)
1.234,00 needs to remain unchanged as not US format (i.e. comma here is used for decimals)
I was thinking of using the following but wasn't sure about it as I am pretty new to Regex:
myVar.replace(/(\d+),(?=\d{3}(\D|$))/g, "$1");
What is best solution here? Note: I just need to cover normal amounts like the above examples, no special cases like letter / number combinations or things like 1,2,3 etc.
This one may suit your needs:
,(?=[\d,]*\.\d{2}\b)
Debuggex Demo
if (string.match(/\.\d{2}$/) {
string = string.replace(',', '');
}
or
string.replace(/,(?=.*\.\d+)/g, '');
Replace /,(?=\d*[\.,])/g with empty string?
http://regexr.com/39v2m
You can use replace() method to remove all the commas. They will be replaced with an empty string. I'm using reg exp with lookahead assertion to detect if a comma is followed by three digits, if so given comma will be removed.
string.replace(/,(?=\d{3})/g, '')
Examples:
'12,345,678.90'.replace(/,(?=\d{3})/g, '')
// '12345678.90'
'1,23,456.78'.replace(/,(?=\d{3})/g, '')
// '1,23456.78'
'$1,234.56'.replace(/,(?=\d{3})/g, '')
// '$1234.56'
This code is worked for me and you can use it in set amount val for remove separators
t.replace(/,(?=\d{3})/g, '')
myVar = myVar.replace(/([.,])(\d\d\d\D|\d\d\d$)/g,'$2');
Removes the period . or comma , when used as a thousand separator.

Determine if a string is only numbers or a comma

How can I determine if a string contains only numbers or a comma?
var x = '99,999,999';
var isMatch = x.match('/[\d|,]/');
The above always returns null.
To be a little more exact:
/^\d{1,3}(?:,\d{3})*$/
Only matches when the number is delimited by a comma after every 3rd digit from the right. (This doesn't account for decimals)
Try this: /^[\d,]+$/ Note that this will not tell you if the number is formatted correctly (i.e. ,99, will be accepted just as 99 or 9,999).
/^(?:\d{1,3}(?:,\d{3})*$|^\d+$)/ while more complex, this regex will test to see if the number is a properly formatted number (it won't accept ,,1,,,1,1111,,1,1,1 only 1,11,111,1,111,1111 etc.)

print number with comma as hundred separator

I have a number like "7847258998" which I want to print with hundred comma separator in javascript.
The result should be:
7,84,72,58,998
i.e the first three digits from right should be grouped together. Remaining digits grouped in chunks of 2. I tried with following:
"7847258998".replace(/\B(?=(\d{3})+(\d{2})+(?!\d))/g, ",")
But it returns: 7,8,4,72,58998. What is the right expression?
Try this:
"7847258998".replace(/\B(?=(\d{2})*(\d{3})$)/g, ",");
I match the end of the string in the lookahead so that I'm always looking for something sane. Otherwise just about anything matches.
Tested on inputs length 1-10.. Enough to decide that it probably works. Pretty inefficient way to do it though, as for each character you have to parse the rest of the string.
But you did ask for a regular expression that does the job =)
function commafy(num)
{
num = num+"";
var re=/(-?\d+)(\d{3})/
while(re.test(num))
{
num=num.replace(re,"$1,$2")
}
return num;
}
function commafyback(num)
{
var x = num.split(',');
return parseFloat(x.join(""));
}
alert(commafy(7847258998))
You can convert the number to a locale string using the en-IN locale.
(7847258998).toLocaleString("en-IN")
If the value is a string, convert it to a number first:
const value = "7847258998"
Number(value).toLocaleString("en-IN")
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

Using Regular Expressions with Javascript replace method

Friends,
I'm new to both Javascript and Regular Expressions and hope you can help!
Within a Javascript function I need to check to see if a comma(,) appears 1 or more times. If it does then there should be one or more numbers either side of it.
e.g.
1,000.00 is ok
1,000,00 is ok
,000.00 is not ok
1,,000.00 is not ok
If these conditions are met I want the comma to be removed so 1,000.00 becomes 1000.00
What I have tried so is:
var x = '1,000.00';
var regex = new RegExp("[0-9]+,[0-9]+", "g");
var y = x.replace(regex,"");
alert(y);
When run the alert shows ".00" Which is not what I was expecting or want!
Thanks in advance for any help provided.
strong text
Edit
strong text
Thanks all for the input so far and the 3 answers given. Unfortunately I don't think I explained my question well enough.
What I am trying to achieve is:
If there is a comma in the text and there are one or more numbers either side of it then remove the comma but leave the rest of the string as is.
If there is a comma in the text and there is not at least one number either side of it then do nothing.
So using my examples from above:
1,000.00 becomes 1000.00
1,000,00 becomes 100000
,000.00 is left as ,000.00
1,,000.00 is left as 1,,000.00
Apologies for the confusion!
Your regex isn't going to be very flexible with higher orders than 1000 and it has a problem with inputs which don't have the comma. More problematically you're also matching and replacing the part of the data you're interested in!
Better to have a regex which matches the forms which are a problem and remove them.
The following matches (in order) commas at the beginning of the input, at the end of the input, preceded by a number of non digits, or followed by a number of non digits.
var y = x.replace(/^,|,$|[^0-9]+,|,[^0-9]+/g,'');
As an aside, all of this is much easier if you happen to be able to do lookbehind but almost every JS implementation doesn't.
Edit based on question update:
Ok, I won't attempt to understand why your rules are as they are, but the regex gets simpler to solve it:
var y = x.replace(/(\d),(\d)/g, '$1$2');
I would use something like the following:
^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)$
[0-9]{1,3}: 1 to 3 digits
(,[0-9]{3})*: [Optional] More digit triplets seperated by a comma
(\.[0-9]+): [Optional] Dot + more digits
If this regex matches, you know that your number is valid. Just replace all commas with the empty string afterwards.
It seems to me you have three error conditions
",1000"
"1000,"
"1,,000"
If any one of these is true then you should reject the field, If they are all false then you can strip the commas in the normal way and move on. This can be a simple alternation:
^,|,,|,$
I would just remove anything except digits and the decimal separator ([^0-9.]) and send the output through parseFloat():
var y = parseFloat(x.replace(/[^0-9.]+/g, ""));
// invalid cases:
// - standalone comma at the beginning of the string
// - comma next to another comma
// - standalone comma at the end of the string
var i,
inputs = ['1,000.00', '1,000,00', ',000.00', '1,,000.00'],
invalid_cases = /(^,)|(,,)|(,$)/;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].match(invalid_cases) === null) {
// wipe out everything but decimal and dot
inputs[i] = inputs[i].replace(/[^\d.]+/g, '');
}
}
console.log(inputs); // ["1000.00", "100000", ",000.00", "1,,000.00"]

Categories

Resources