humanizemoney

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 18, 2025 License: MIT Imports: 5 Imported by: 0

README

humanizemoney

A Go package for formatting monetary amounts with proper localization support. It uses the Unicode CLDR (Common Locale Data Repository) to ensure accurate number formatting across different locales and currencies. Based on https://github.com/govalues/money.

Features

  • Locale-aware money formatting
  • Support for different currency symbols and positions
  • Proper decimal and grouping separators based on locale
  • Configurable decimal precision
  • Optional trimming of trailing zeros
  • Based on official Unicode CLDR data

Note

  • Numeric Representation: Floating Point
  • Precision: 19 digits
  • Default Rounding: Half to even

Installation

go get github.com/dejurin/humanizemoney

Usage

package main

import (
	"fmt"

	"golang.org/x/text/language"

	"github.com/dejurin/humanizemoney"
)

func main() {

	h := humanizemoney.New(language.English)      // Use English locale
	h.CurrencyDisplay = humanizemoney.DisplayCode // Show currency code
	h.NoGrouping = false                          // Remove grouping
	h.TrimZeros = true                            // Remove trailing zeros (Trim returns an amount with trailing zeros removed up to the given scale.)

	amount := "9999.4900"

	// USD 9,999.490
	result, err := h.Formatter(amount, "USD", 3) // Format amount to USD with 3 decimal places

	if err != nil {
		panic(err)
	}

	fmt.Println(result)
}

Benchmark

Below are the benchmark results performed on an Apple M3 Max (darwin/arm64) for the github.com/dejurin/humanizemoney package. The table includes a column showing the percentage difference relative to BenchmarkBojanzFormatter-16 https://github.com/bojanz/currency as a positive improvement. The -16 suffix in the benchmark name indicates that the test was run with GOMAXPROCS = 16 (or on a system with 16 logical CPUs).

Benchmark Iterations ns/op ns/op Improvement B/op B/op Improvement allocs/op allocs/op Improvement
BenchmarkBojanzFormatter-16 938421 1283 – (baseline) 1856 – (baseline) 28 – (baseline)
BenchmarkHumanizeMoneyFormatter-16 2068676 540.8 +57.84% 472 +74.56% 15 +46.43%
  • Iterations — total number of benchmark iterations.
  • ns/op — average time in nanoseconds per operation.
  • B/op — bytes allocated per operation.
  • allocs/op — memory allocations per operation.
  • Improvement columns compare against BenchmarkBojanzFormatter-16 (baseline).

Errors

The package provides two types of errors:

  • UnsupportedLocaleError: Returned when the specified locale is not supported
  • FailedParseAmount: Returned when the input amount string cannot be parsed

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.


Acknowledgements

Special thanks to the creators of github.com/govalues/money for providing a robust foundation for this library.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var NumberSystemMap = map[language.Tag]NumberSystem{}/* 725 elements not displayed */
View Source
var SymbolMap = map[string]string{}/* 106 elements not displayed */

Functions

This section is empty.

Types

type Display

type Display uint8

Display represents how the currency should be shown in the formatted output.

const (
	// DisplaySymbol shows the currency symbol (e.g., "$" for USD).
	DisplaySymbol Display = iota
	// DisplaySymbolCode shows the currency symbol (e.g., "$" for USD) or code if symbol is not available (e.g., "USD" for USD).
	DisplaySymbolCode
	// DisplayCode shows the currency code (e.g., "USD").
	DisplayCode
	// DisplayNone shows no currency indicator.
	DisplayNone
)

Constants for Display

type FailedParseMoney added in v0.1.0

type FailedParseMoney struct {
	// The original value that failed to parse
	Value string
	// The underlying error
	Err error
}

FailedParseAmount represents an error that occurs when parsing a monetary amount fails.

func (FailedParseMoney) Error added in v0.1.0

func (e FailedParseMoney) Error() string

Error returns a string representation of the error.

type Humanizer

type Humanizer struct {
	// Locale specifies the language and region for formatting rules
	Locale language.Tag
	// NoGrouping disables digit grouping when true (e.g., 1000 vs 1,000)
	NoGrouping bool
	// TrimZeros removes trailing zeros in decimal places when true
	TrimZeros bool
	// CurrencyDisplay determines how the currency is displayed
	CurrencyDisplay Display
}

Humanizer contains configuration for formatting monetary values.

func New

func New(locale language.Tag) *Humanizer

New creates a new Humanizer with the specified locale and default settings.

func (*Humanizer) FormatDecimal added in v0.1.0

func (h *Humanizer) FormatDecimal(decimal decimal.Decimal, currencyCode string, precision int) (string, error)

FormatDecimal formats a decimal.Decimal value according to locale rules. It takes a Decimal object, currency code, and precision for decimal places. Returns the formatted string and any error that occurred.

func (*Humanizer) FormatMoney added in v0.1.0

func (h *Humanizer) FormatMoney(amount money.Amount, currencyCode string, precision int) (string, error)

FormatMoney formats a money.Amount value according to locale rules. It takes an Amount object, currency code, and precision for decimal places. Returns the formatted string and any error that occurred.

func (*Humanizer) Formatter

func (h *Humanizer) Formatter(value string, currencyCode string, precision int) (string, error)

Formatter formats a string representation of a monetary value according to locale rules. It takes a value string, currency code, and precision for decimal places. Returns the formatted string and any error that occurred.

type NumberPattern

type NumberPattern struct {
	// Prefix is the string that comes before the number
	Prefix string
	// Suffix is the string that comes after the number
	Suffix string
	// DecimalSep is the decimal separator character
	DecimalSep string
	// GroupSep is the grouping separator character
	GroupSep string
	// GroupSizes defines the sizes of digit groups
	GroupSizes []int
	// CurrencyAtStart indicates if the currency symbol should appear before the number
	CurrencyAtStart bool
}

NumberPattern holds the formatting pattern for numbers in a specific locale.

type NumberSystem

type NumberSystem struct {
	Standard   string
	DecimalSep string
	GroupSep   string
}

type UnsupportedLocaleError

type UnsupportedLocaleError struct {
	// The locale that is not supported
	Locale language.Tag
}

UnsupportedLocaleError represents an error that occurs when a locale is not supported.

func (UnsupportedLocaleError) Error

func (e UnsupportedLocaleError) Error() string

Error returns a string representation of the error.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL