How to replace all occurrences of a specific digit in a floating-point number with TypeScript

1 Answer

0 votes
function replaceAllDigits(num: number, oldDigit: string, newDigit: string): number {
  // Format the number to a string with 3 decimal places
  const strNum = num.toFixed(3);

  // Create a global regular expression to replace all occurrences
  const regex = new RegExp(oldDigit.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
  const modifiedStr = strNum.replace(regex, newDigit);

  // Convert the modified string back to a number
  return parseFloat(modifiedStr);
}

console.log(replaceAllDigits(82420.291, '2', '7').toFixed(3));
console.log(replaceAllDigits(111.11, '1', '5').toFixed(3));



/*
run:

87470.791
555.550 

*/

 



answered 16 hours ago by avibootz

Related questions

...