Home > Backend Development > Golang > How to Format Integers with Thousands Commas using fmt.Printf in Go?

How to Format Integers with Thousands Commas using fmt.Printf in Go?

Barbara Streisand
Release: 2024-11-02 09:19:31
Original
365 people have browsed it

How to Format Integers with Thousands Commas using fmt.Printf in Go?

Comma-Separated Integers with fmt.Printf

In Go, the fmt.Printf function provides a versatile way to format and print various data types, including integers. However, by default, fmt.Printf does not support outputting integers with thousands commas.

To address this need, the golang.org/x/text/message package offers localized formatting, allowing you to print numbers according to the cultural norms of different languages.

Utilizing the message Package

To use the message package:

  1. Import the package into your Go program:

    <code class="go">import (
     "golang.org/x/text/language"
     "golang.org/x/text/message"
    )</code>
    Copy after login
  2. Create a message Printer for a specific language. In this case, we use English:

    <code class="go">p := message.NewPrinter(language.English)</code>
    Copy after login
  3. Use the Printer to format and print your integer using "%d":

    <code class="go">p.Printf("%d\n", 1000)</code>
    Copy after login

Example Output

Running the provided code will print the integer 1000 with a thousands comma separator:

1,000
Copy after login

This approach leverages the Unicode CLDR (Common Locale Data Repository) to provide accurate and culturally appropriate formatting for various languages and locales.

The above is the detailed content of How to Format Integers with Thousands Commas using fmt.Printf in Go?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template