Home > Backend Development > Golang > How to Output Numbers with Thousands Commas in Go\'s fmt.Printf?

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

Patricia Arquette
Release: 2024-10-31 06:18:30
Original
285 people have browsed it

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

Outputting Numbers with Thousands Comma in Go's fmt.Printf

Go's fmt.Printf function provides formatting options for outputting various data types. However, it does not have an explicit support for adding thousands commas to numbers.

Overcoming the Absence of Commas

To add thousands commas to numbers, a third-party library, such as golang.org/x/text/message, can be utilized. This library enables the formatting of numbers according to localized conventions.

Implementation

To use golang.org/x/text/message for outputting numbers with thousands commas:

  1. First, import the library:

    <code class="go">import (
     "golang.org/x/text/language"
     "golang.org/x/text/message"
    )</code>
    Copy after login
  2. Create a new message.Printer object, specifying the desired language for formatting:

    <code class="go">p := message.NewPrinter(language.English)</code>
    Copy after login
  3. Call the Printf method on the message.Printer object, passing in the number to be formatted:

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

Example

The following example prints the number 1000 with thousands commas using golang.org/x/text/message:

<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

By using golang.org/x/text/message, it becomes possible to conveniently output numbers with thousands commas, adhering to localized formatting conventions for different languages.

The above is the detailed content of How to Output Numbers with Thousands Commas in Go\'s fmt.Printf?. 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