Home > Web Front-end > JS Tutorial > How to Format Numbers with Thousands Separators in JavaScript?

How to Format Numbers with Thousands Separators in JavaScript?

DDD
Release: 2024-12-31 19:07:10
Original
773 people have browsed it

How to Format Numbers with Thousands Separators in JavaScript?

Formatting Numbers with Thousands Separators in JavaScript

Question:

How to use JavaScript to convert integers Format as number with thousands separator? For example, display the number 1234567 as "1,234,567".

Current implementation:

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

A simpler and more elegant method:

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

This method uses regular expressions Expression to find occurrences after every three digits (B(?=(d{3}) (?!d))) and replace it with a comma (,).

Floating point number processing:

This method can also handle floating point numbers. Just convert the floating point number into a string and then format it:

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

console.log(numberWithCommas(1234567.89)); // "1,234,567.89"
Copy after login

The above is the detailed content of How to Format Numbers with Thousands Separators in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template