Page 1 of 1

Converting a salary input string to number

Posted: 03 Nov 2020, 06:08
by Marius
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.

Converting a salary input string to number

Posted: 03 Nov 2020, 07:32
by 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