-2

i am using toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")

eg,

var n = 803427325.0326

n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") 

it will show n = 803,427,325.0,326

but I need it like

n = 803,427,325.0326

and i update the regex to -> toString().replace(/\d(?=\d*.\d)(?=(?:\d{3})+(?!\d))/g, "$&,")

var n = 803427325.0326

n.toString().replace(/\d(?=\d*.\d)(?=(?:\d{3})+(?!\d))/g, "$&,")

and the result is fine

n = 803,427,325.0326

but for n = 803427325

but it result 803427325

i need it like 803,427,325

  • 3
    Consider not doing this manually, rather use [toLocalString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString) etc. – Dave Newton May 12 '21 at 15:22
  • @DaveNewton good suggestion. There are also a plethora of libraries for internationalisation of data, including numbers, to choose from. Just in case `toLocaleString()` is lacking in some respect. – VLAZ May 12 '21 at 15:26
  • @DaveNewton - that's probably worth it's own answer. It's the one I'd accept. – JDB May 12 '21 at 15:27
  • @JDBstillremembersMonica something like this?: [How to format numbers using JavaScript?](https://stackoverflow.com/q/5882994) – VLAZ May 12 '21 at 15:31
  • @VLAZ - It's the same API to a different effect. I wouldn't consider that a duplicate question on the surface, though. This would probably be more relevant to the OP: https://stackoverflow.com/a/17663871/211627 – JDB May 12 '21 at 16:16

3 Answers3

2

You could assert a dot at the right, and you might also omit the capture group.

\B(?=\d*\.)(?=(\d{3})+(?!\d))
  • \B Match at a position that a word boundary does not match
  • (?=\d*\.) Positive lookahead, assert a . at the right
  • (?= Positive lookahead
    • (?:\d{3})+(?!\d) Match 1+ repetitions of 3 digits not followed by a digit
  • ) Close lookahead

Regex demo

var n = 803427325.0326;

n = n.toString().replace(/\B(?=\d*\.)(?=(?:\d{3})+(?!\d))/g, ",");
console.log(n);
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
2

Assuming for some reason that you don't have access to n.toLocaleString(), which would format the number with thousands separators appropriate to your user's locale settings, you can simply split on the decimal, apply the regex to the first half, then recombine.

You can, of course, accomplish the same with a much more complex regex, but no one needs a more complex regex in their lives if they can avoid it.

let n = 803427325.0326
const parts = n.toString().split(".");

n = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
if (parts[1]) n = `${n}.${parts[1]}`;

console.log(n)
JDB
  • 25,172
  • 5
  • 72
  • 123
0

var n= 803427325.0326;

var result=n.toString().replace(/^[+-]?\d+/, function(int) {
              return int.replace(/(\d)(?=(\d{3})+$)/g, '$1,');
            });
            
            console.log(result);