Home >Backend Development >Golang >Can fmt.Printf Display Numbers with Thousands Commas?

Can fmt.Printf Display Numbers with Thousands Commas?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 04:56:30574browse

Can fmt.Printf Display Numbers with Thousands Commas?

Formatting Numbers with Thousands Commas Using fmt.Printf

Go's fmt.Printf function offers comprehensive formatting options for outputting numbers. However, it may not be immediately apparent how to add thousands commas to your output.

Question:

Can fmt.Printf be leveraged to display a number with thousands commas? How can we modify the format to achieve this?

Answer 1 (Without fmt.Printf):

For localized formatting with thousands commas and support for various languages, use golang.org/x/text/message. Here's an example:

package main

import (
    "golang.org/x/text/language"
    "golang.org/x/text/message"
)

func main() {
    p := message.NewPrinter(language.English)
    p.Printf("%d\n", 1000)

    // Output:
    // 1,000
}

In this example, the message.NewPrinter is configured for the English language. The %d format specifier is used to denote an integer, and the Printer handles the comma formatting automatically.

The above is the detailed content of Can fmt.Printf Display Numbers with Thousands Commas?. 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