-1
const numberWithCommas = (x) => {
 return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

I have this function in which if a number is sent like 1223.00001 It will return like 1,223.00,001 but I would like to get 1,223.00001 ! I would like to get decimals without commas! This question is giving me different answer !

Bharadwaj
  • 11
  • 5
  • 1
    Note: When I run your function on `1223.00001`, I get `1,223.00,001` instead of `1,223.00,00,1` (which you use in your question). Ensure that your inputs and outputs are correct in your question. – Andrew Fan Jun 09 '18 at 03:10
  • 1
    what does `1223.00001.toLocaleString('en', {maximumFractionDigits:20})` do? probably what you want :p – Jaromanda X Jun 09 '18 at 03:17
  • *"This question is giving me different answer !"* Have you actually looked at the bottom of the accepted answer? Or the second and third highest voted answers? – Felix Kling Jun 09 '18 at 03:25

1 Answers1

0

You may add a positive lookahead to your regex which asserts that a decimal point follows. This guarantees that the replacement only happens to the whole number component.

x = "1223.00001";
x = x.replace(/\B(?=(\d{3})+(?!\d))(?=.*\.)/g, ",");
console.log(x);

One rather brute force option would be to just apply your current regex to the whole number side of the input. Then, concatenate that replaced result with the decimal portion.

x = "1223.00001";
top = x.replace(/\..*$/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
bottom = x.replace(/^.*\./, "");
console.log(top + "." + bottom);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360