Converting a salary input string to number

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 97

Converting a salary input string to number

I have the following problem:
1. eliminate thousand separators(,) 5,555 to 5555.
2. if the user inputs 55,66 replace , with . and get the value 55.66
3. if user inputs both , and . eg. 1,234.55 gets the value 1234.55

How can I solve it in JavaScript.

Admin
Try the function from the following code:

Code: Select all

function salNr(s){
  //If there is comma before the last two digit, replace it with dot, else remove the comma
  return s.replace(/,([0-9]{1,2})$/, '.$1').replace(',', '') *1;
}

let arr =['54,55', '5,456', '1,234.56'];

console.log(salNr(arr[0]));  // 54.55
console.log(salNr(arr[1]));  // 5456
console.log(salNr(arr[2]));  // 1234.56

Similar Topics