How do I take a comma in a thousand digits in JavaScript?

Asked 1 years ago, Updated 1 years ago, 95 views

I'd like to take a comma in a thousand digits when I print the integrer in JavaScript. For example, If you have 1234567, I want to print it out like 1,234,567

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1,$2");
    return x;
}

I did it like this. But is there a simpler and better way than this?

javascript format

2022-09-22 22:08

1 Answers

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


2022-09-22 22:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.