How to Add Commas to Numbers in Go\'s fmt.Printf Output?

Barbara Streisand
Release: 2024-10-30 18:58:02
Original
547 people have browsed it

How to Add Commas to Numbers in Go's fmt.Printf Output?

Adding Commas to Go's fmt.Printf Output

fmt.Printf is a versatile formatting function in Go, but it lacks the ability to add comma separators to integers by default. This limitation can be encountered when formatting numeric values such as currency or large numbers for display purposes.

To overcome this, we can leverage the golang.org/x/text/message library, which provides localized formatting capabilities.

Code Example:

<code class="go">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
}</code>
Copy after login

In this example, we use the NewPrinter function to create a message.Printer object with the specified language (English in this case). The Printf method formats the integer 1000 using the localized formatting rules for English, which include the addition of commas for numbers over 999. By default, the printer uses the CLDR (Common Locale Data Repository) database for formatting rules, ensuring a standardized and localized output.

The above is the detailed content of How to Add Commas to Numbers in Go\'s fmt.Printf Output?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!