Home  >  Article  >  Backend Development  >  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
Barbara StreisandOriginal
2024-11-02 09:19:31275browse

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>
  2. Create a message Printer for a specific language. In this case, we use English:

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

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

Example Output

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

1,000

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!

Statement:
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