Check for numeric value with optional commas javascript - javascript

I need to check a value if it is numeric and optionally contains commas.
I tried
var input=3433;
var pattern=/^[1-9]\d{0,2}(\.\d{3})*(,\d+)?$/;
pattern.test(input);
but it always gave me false;
I don't want to use $.isNumeric as it does not check for commas.

Assuming you're using the comma as a thousands separator, the easiest way to do this is to just remove the commas when converting:
var num = +str.replace(/,/g, '');
if (!isNaN(num)) {
// It's a valid number
}
If your locale uses . as the thousands separator and , as a decimal point (as your regex seems to suggest), since JavaScript always uses them the other way around, we have more to change in the string first:
var num = +str.replace(/\./g, '').replace(/,/g, ".");
if (!isNaN(num)) {
// It's a valid number
}

I must process in different ways strings and string-numbers.
So I must test if a string is a string-number (not a valid number), using the locale convention.
My rude solution is:
var num = +str.replace(/\./g, '').replace(/,/g, '');
if (!isNaN(num))...
This works with USA, EUR locales. The control about 'valid number' is done after, car I wanna send detailed WARNING/ERROR messages to user.

Your sample var input is not matched by your regex because of the dot.
You could do:
var input=3433;
var pattern=/^[1-9]\d{0,2}(\.?\d{3})*(,\d+)?$/;
// the dot is optional __^
pattern.test(input);
This regex will match:
123
1234
1.234
123,45
1234,567
1.234,56
1.234.567,89

Related

How to round of prices with comma's instead of dots?

In The Netherlands we use comma's in numbers where in other countries dots would be used. For example we use 39,99 and in other countries 39.99.
In a feed with prices we would have prices with such comma use, but I'm having trouble using those as numbers and rounding them by two digits behind the comma (or behind the dot really).
var num1 = "39,1234";
var num = parseInt(num1);
var n = num.toFixed(2);
console.log(n);
Here is such a number. I would like it to result in 39,12. They way I was thinking is then first use it as a string. Then turn that string into a number and use toFixed to round it of to two digets. But it results in 39,00 instead of 39,12.
Perhaps I'm thinking wrong and I should use some other way to make 39,1234 to be seen as 39.1234 so that it is rounded correctly as a number?
How can I used 39,1234 as a number 39,1234 instead of a string? So that I wouldn't have to go through a feed and replace commas by dots first in all my prices?
Edit: Regex version
Earlier I didn't realize that OP originally wanted it back to the format "xx,xx". This is a more elegant solution:
var num1 = "39,1234";
let n = num1.replace(/(?<=,\d{2})(\d*)$/,"");
console.log(n); //32,12
Regex explanation:
(?<=,\d){2} begins a lookbehind match for , followed by digits \d, 2 of them {2}. Lookbehind matches are not replaced.
(\d*)$ when we've found the lookbehind pattern, we match more digits \d, all * of them, till we reach end of string $. This is the match that will get replaced.
Original Solution
What you want is:
var num1 = "39,1234";
var n = parseFloat(num1.replace(",",".")).toFixed(2);
console.log(n); //39.12
// replaces it back to ",", but now it's a string!
n = n.replace(".",",")
console.log(n); //39,12
Explanation:
First replace "," with "." with replace()
Convert to float (not integer) with parseFloat()
Set to 2 decimal places with .toFixed(2)
Replace "." with ",". But now it's a string!
Note: this will not work if the currency value contains . as a thousandth separator. e.g. "40.200,1576". If that's the case, add another line num1 = num1.replace(".","") to strip out the separator before passing it to the parseFloat(...) line.
Try this
comdecimal= num1.replace(".","")
alert(comdecimal);
dotdecimal= comdecimal.replace(",",".")
alert(dotdecimal);
dotdecimal = Math.round(dotdecimal* 100) / 100;
alert(dotdecimal);
Since you're working with currency, I'd recommend using JS ES6 designated NumberFormat feature. Your code should look like this and be easily reused:
const formatter = new Intl.NumberFormat('nl-NL', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 2
});
console.log(formatter.format('145,53'.replace(',','.')));
//"€ 145,53"

Javascript Regex doesn't match with my String

I have the following String :
var resultLine= "[UT] - GSM incoming call : STEP 1 - Simulate reception from server (1)Rerun3713 msAssertion ok"
And the following code which is responsible to check of the String matched with the Regex :
var resultRE = /^([ \w-]*: )?(.+) \((\d+), (\d+), (\d+)\)Rerun/;
var resultMatch = resultLine.match(resultRE);
if (resultMatch) {
return true;
} else {
return false;
}
In this case, i have an error in my Regex because i always get "false".
Where is my mistake ?
I would recommend the following pattern based on what it appears you are looking for:
var resultRE = /^([\[ \w\]-]*: )(.+) \(([0-9, ]*)\)Rerun(.*)$/
This should force all capture groups to exist, even if they are empty, and will allow for multiple numbers before Rerun as you seem to expect.
This matches nothing in your string
([ \w-]*: )?
Since it was optional, that doesn't matter because it gets caught by the all inclusive
(.+)
If you were trying to match the [UT] part with it's separator, it would look something like this
(\[\w+\][\s\-]*)?
As noted in the comments, you only have one number in parentheses but your regex requires three sets of them, separated by commas. This will allow any number of numbers, separated by commas indefinitely (I don't know if there's a limit or not).
\((\d+,\s)*(\d+)\)
If you need something more specific, you'll have to be more specific about what template your matching, not a specific case. But the best I can figure with what you've provided is
^(\[\w\][\s\-]*)?(.+)\((\d+,\w)*(\d+)\)Rerun
var resultRE = /\((\d+)(?:, (\d+))?(?:, (\d+))?\)Rerun/;
if (resultRE.test(resultLine)) {
var num1 = RegExp.$1,
num2 = RegExp.$2,
num3 = RegExp.$3;
}

Splitting a string at special character with JavaScript

I am trying to "intelligently" pre-fill a form, I want to prefill the firstname and lastname inputs based on a user email address, so for example,
jon.doe#email.com RETURNS Jon Doe
jon_doe#email.com RETURN Jon Doe
jon-doe#email.com RETURNS Jon Doe
I have managed to get the string before the #,
var email = letters.substr(0, letters.indexOf('#'));
But cant work out how to split() when the separator can be multiple values, I can do this,
email.split("_")
but how can I split on other email address valid special characters?
JavaScript's string split method can take a regex.
For example the following will split on ., -, and _.
"i-am_john.doe".split(/[.\-_]/)
Returning the following.
["i", "am", "john", "doe"]
You can use a regular expression for what you want to split on. You can for example split on anything that isn't a letter:
var parts = email.split(/[^A-Za-z]/);
Demo: http://jsfiddle.net/Guffa/xt3Lb9e6/
You can split a string using a regular expression. To match ., _ or -, you can use a character class, for example [.\-_]. The syntax for regular expressions in JavaScript is /expression/, so your example would look like:
email.split(/[\.\-_]/);
Note that the backslashes are to prevent . and - being interpreted as special characters. . is a special character class representing any character. In a character class, - can be used to specify ranges, such as [a-z].
If you require a dynamic list of characters to split on, you can build a regular expression using the RegExp constructor. For example:
var specialChars = ['.', '\\-', '_'];
var specialRegex = new RegExp('[' + specialChars.join('') + ']');
email.split(specialRegex);
More information on regular expressions in JavaScript can be found on MDN.
Regular Expressions --
email.split(/[_\.-]/)
This one matches (therefore splits at) any of (a character set, indicated by []) _, ., or -.
Here's a good resource for learning regular expressions: http://qntm.org/files/re/re.html
You can use regex to do it, just provide a list of the characters in square brackets and escape if necessary.
email.split("[_-\.]");
Is that what you mean?
You are correct that you need to use the split function.
Split function works by taking an argument to split the string on. Multiple values can be split via regular expression. For you usage, try something like
var re = /[\._\-]/;
var split = email.split(re, 2);
This should result in an array with two values, first/second name. The second argument is the number of elements returned.
I created a jsFiddle to show how this could be done :
function printName(email){
var name = email.split('#')[0];
// source : http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript
var returnVal = name.split(/[._-]/g);
return returnVal;
}
http://jsfiddle.net/ts6nx9tt/1/
If you define your seperators, below code can return all alternatives for you.
var arr = ["_",".","-"];
var email = letters.substr(0, letters.indexOf('#'));
arr.map(function(val,index,rest){
var r = email.split(val);
if(r.length > 1){
return r.join(' ');
}
return "";
}
);

Javascript numeric input (regex) validation rules

I'm a bit stuck here.
With regards to the input of accounting data, the analyst requested a specific set of rules on the input of decimal data in text boxes.
Since I have not studied regular expressions at this point, and because I have very strict deadlines to attend with each a lot of work, I request your help.
The rules are (on blur):
IE8+ compatible;
Set default at 2 digits behind the comma;
Disallow other characters than ".", "," and numeric characters;
If there are multiple separators in the returned number, only keep the last one.
Explanation:
Employees may have different regional settings, and comma / dot may be used as either decimal or thousands separator.
In case an employee copy - pastes both the thousand and the decimal separator, it has to be ignored.
What I've done so far, but doesn't fulfill the requirements:
http://jsfiddle.net/NxFHL/1/
$('#test_rules.numeric').on('blur', function(){
var myString = $('#test_rules.numeric').val();
myString = parseFloat(myString.replace(/[^\d.-]/g, ''));
myString = toFixed(myString, 2);
console.log(myString);
});
function toFixed(value, precision) {
var power = Math.pow(10, precision || 0);
return
String(Math.round(value * power) / power);
}
The regular expression used doesn't work correctly as it only accepts dot, not comma.
Also I am not sure about how I should make it so that only the last separator stays (so that the thousands separator gets ignored).
Try this function:
function parseInputNum(val) {
var sep = val.lastIndexOf('.') > val.lastIndexOf(',')? '.' : ',';
var arr = val.replace(new RegExp('[^\\d'+sep+']+', 'g'), '')
.match(new RegExp('(\\d+(?:['+sep+']\\d+|))$'));
return arr? arr[1].replace(/[,]/g, '.') : false;
}
You can use this pattern:
^(?:[1-9](?:[0-9]{0,2}(?:([.,])[0-9]{3})?(?:\1[0-9]{3})*|[0-9]*)|0)(?!\1)[.,][0-9]{2}$
This pattern will check numbers like:
123,45
12,45
0.45
123,456,789.12
1234.56
123.456.789,12
but not numbers like:
12.23.45,12
012,345,678,91
1234,567.89
123,456,78
To convert the string into a number you must remove the thousand delimiter before. This can easily be done since the delimiter (if present) is in the capturing group 1. You must probably too replace the , by the . if it is used as decimal separator.

Commas messing with number input in Javascript

I have a page with some elements that are controlled by the user. One of these is a text input field, where the user is supposed to input a number. Everything works well if the user only inputs digits (EG 9000), but is the user uses comma notation (the being 9,000) javascript doesn't take the input as an integer.
How can I remove the commas and/or force the input to an integer? I tried using parseint(), but it doesn't seem to work with commas.
Use a global regular expression to replace all commas with an empty string:
var str = "12,345,678";
str = str.replace(/,/g, "");
parseInt(str, 10);
or even better
var s="jdjsghd0182.99";
var str = parseFloat(s.replace(/[^0-9 | ^.]/g, ''));
Or even better, given the general unreliability of user input, use this to get rid of all non-numeric characters:
var s = "9,Ljk876";
var t = parseInt(s.replace(/[^0-9]/g, ''));
alert ("s:" + s + ", t:" + t);
maybe
parseint(ny9000withCommas.replace(/\,/g,""))
lets talk about the restriction :
you can/should allow the user to enter both 9000 & 9,000
you can check validy via REGEX.
in the server side - you should eleminate the commas and treat it as integer.

Categories