unit

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package unit provides utilities for handling units including human-readable unit formatting, parsing, and registration of custom units and formatting systems.

Unit Systems:

This package supports two built-in unit systems:

1. IEC Binary Units (base-2): Used by Binary() option and FormatBinary functions.

  • Units increase by powers of 1024 (2^10)
  • Prefixes include Ki, Mi, Gi, Ti, Pi, etc.
  • Often used for memory and storage in computing contexts
  • Example: 1024 bytes = 1 KiB (kibibyte)

2. SI Decimal Units (base-10): Used by Decimal() option and FormatDecimal functions.

  • Units increase by powers of 1000 (10^3)
  • Prefixes include k, M, G, T, P, etc.
  • Often used for data transmission rates and disk marketing
  • Example: 1000 bytes = 1 kB (kilobyte)

Supported Units:

The package natively supports the following unit types:

  • Byte: Used for data storage (B)
  • Bit: Used for data transmission (b)
  • Hertz: Used for frequencies (Hz)

Formatting Functions:

This package provides approaches to formatting values with units:

1. Option-Based Approach (Most Flexible):

  • Format: Returns a Value struct that provides both the scaled value and full formatting information. Configure with option functions like Binary(), Decimal(), WithUnit(), WithPrecision(), etc.

Examples:

// Basic usage
fmt.Println(Format(1024, Binary(), WithUnit(Byte))) // Output: 1 KiB

// Using options
fmt.Println(Format(1500,
    Decimal(),
    WithUnit(Bit),
    WithPrecision(2),
    WithPlural())) // Output: 1.50 kilobits

2. Simplified Convenience Functions:

  • FormatBinary/FormatDecimal: Format values without a unit type using standard binary or decimal systems.
  • FormatBinaryUnit/FormatDecimalUnit: Format with specific built-in unit types (Byte, Bit, Hertz) using standard binary or decimal systems.

These convenience functions internally use Format with specific option combinations.

Returned Value:

The Format function returns a Value struct which includes:

  • Scaled: The scaled numeric value.
  • Prefix: Information about the unit prefix (e.g., "kilo", "Ki").
  • Unit: A Descriptor containing information about the unit (e.g., "byte", "bit").

The Value struct implements fmt.Stringer, so it can be used directly in string contexts like fmt.Printf or fmt.Println.

Custom Units:

Beyond the built-in units (Byte, Bit, Hertz), you can register your own custom units. This allows the formatting functions to work with units specific to your domain.

  • Register / MustRegister: Use these functions to define a new unit. You provide a Descriptor containing the unit's Symbol, Singular name, and Plural name. MustRegister panics on error, while Register returns an error.
  • Descriptor: This struct holds the textual representations of a unit. It also includes the Unit identifier itself.
  • List / Names / Describe / Unit.Info: Functions to query registered units.

Example:

// Register a custom "pixel" unit
UnitPixel := unit.MustRegister(unit.Descriptor{
    Symbol:   "px",
    Singular: "pixel",
    Plural:   "pixels",
})

// Use the custom unit in formatting
fmt.Println(unit.Format(2048, unit.Decimal(), unit.WithUnit(UnitPixel))) // Output: 2 kpx
fmt.Println(unit.Format(1, unit.Decimal(), unit.WithUnit(UnitPixel)))    // Output: 1 px

Custom Formatting Systems:

If the standard SI (base-10) or IEC (base-2) scaling doesn't fit your needs, you can define custom formatting systems with different boundaries and prefix names/symbols.

  • FormatSystem: Represents a custom system with its name, scaling boundaries, and prefix map.
  • RegisterFormatSystem: Registers a new FormatSystem globally by name.
  • GetFormatSystem: Retrieves a registered system by name.
  • WithSystem / WithSystemByName: FormatOptions to apply a custom system during formatting with Format.

Example:

Define a simple time formatting system (seconds, minutes, hours):

timeSystem := unit.RegisterFormatSystem(
    "time",
    []float64{3600, 60}, // Boundaries (hour, minute)
    map[float64]unit.Prefix{
        3600: {Name: "hour", Symbol: "h"},
        60:   {Name: "minute", Symbol: "m"},
    },
)
UnitSecond := unit.MustRegister(unit.Descriptor{Symbol: "", Singular: "", Plural: "s"})

Format a duration using the custom system:

duration := 3725.0 // seconds
fmt.Println(unit.Format(duration, unit.WithSystem(timeSystem), unit.WithUnit(UnitSecond), unit.WithPrecision(1))) // Output: 1.0 h

Parsing:

The Parse function attempts to interpret strings containing numbers and standard units (e.g., "1.5 KB", "1024", "500 MHz"). It currently only supports built-in SI/IEC prefixes and the built-in units (Byte, Bit, Hertz). Custom registered units and custom format systems are **not** supported by the Parse function in this version.

When to Use Each System:

  • Use binary (IEC) units when working with computer memory, storage capacities, or when communicating with technical audiences.
  • Use decimal (SI) units when dealing with data transfer rates, disk marketing, or when communicating with general audiences.

Choose the appropriate formatting approach and extensibility features based on your specific use case and audience expectations.

Index

Constants

View Source
const (
	// IEC binary prefixes as defined in IEC 80000-13
	Kibi  float64 = 1024
	Mebi  float64 = 1048576
	Gibi  float64 = 1073741824
	Tebi  float64 = 1099511627776
	Pebi  float64 = 1125899906842624
	Exbi  float64 = 1152921504606846976
	Zebi  float64 = 1180591620717411303424
	Yobi  float64 = 1208925819614629174706176
	Robi  float64 = 1237940039285380274899124224
	Quebi float64 = 1267650600228229401496703205376

	// SI decimal prefixes as defined in ISO 1000
	Kilo   float64 = 1000
	Mega   float64 = 1000000
	Giga   float64 = 1000000000
	Tera   float64 = 1000000000000
	Peta   float64 = 1000000000000000
	Exa    float64 = 1000000000000000000
	Zetta  float64 = 1000000000000000000000
	Yotta  float64 = 1000000000000000000000000
	Ronna  float64 = 1000000000000000000000000000
	Quetta float64 = 1000000000000000000000000000000
)

Variables

View Source
var (
	// SIDecimalBoundaries represents the boundaries for SI decimal prefixes
	// sorted in descending order.
	SIDecimalBoundaries = []float64{Quetta, Ronna, Yotta, Zetta, Exa, Peta, Tera, Giga, Mega, Kilo}

	// IECBinaryBoundaries represents the boundaries for IEC binary prefixes
	// sorted in descending order.
	IECBinaryBoundaries = []float64{Quebi, Robi, Yobi, Zebi, Exbi, Pebi, Tebi, Gibi, Mebi, Kibi}

	// DataUnits contains units related to data storage/transfer
	DataUnits = []Unit{Byte, Bit}

	// FrequencyUnits contains units related to frequency
	FrequencyUnits = []Unit{Hertz}

	// AllUnits contains all built-in units
	AllUnits = []Unit{Byte, Bit, Hertz}
)
View Source
var DefaultFormatOptions = FormatOptions{
	Precision:     0,
	UseSpace:      true,
	UsePluralUnit: false,
	PrefixFormat:  PrefixFormatShort,
	FormatStyle:   DecimalFormat,
}

DefaultFormatOptions provides default formatting settings

Functions

func BuiltinFormatSystems

func BuiltinFormatSystems() map[string]*FormatSystem

BuiltinFormatSystems returns a map of all built-in format systems

func Convert

func Convert[T number](value T, fromUnit, toUnit float64) float64

Convert transforms a value from one unit scale to another by applying the appropriate conversion factor. This allows explicit conversion between different unit magnitudes.

Parameters:

  • value: The value to convert
  • fromUnit: The unit scale of the input value (e.g., 1 for base unit, Kilo for kilos, Mebi for mebibytes)
  • toUnit: The unit scale to convert to (e.g., Mega for megabytes, Gibi for gibibytes)

Examples:

Convert(1, Mega, Kilo)    // Convert 1 MB to KB = 1000 KB
Convert(1, Mebi, 1)       // Convert 1 MiB to bytes = 1048576 bytes
Convert(1024, 1, Kibi)    // Convert 1024 bytes to KiB = 1 KiB

Converting between units

bytes := 1024 * 1024 // 1 MiB in bytes
megabytes := unit.Convert(bytes, 1, unit.Mebi) // Convert from bytes to MiB
fmt.Println(megabytes) // Output: 1

Returns the converted value in the requested unit scale.

func Names

func Names() []string

Names returns the names of all registered units

Types

type Descriptor

type Descriptor struct {
	// Unit is the identifier for this unit type, returned by Register and used
	// internally.
	Unit Unit
	// Symbol is the short textual representation (e.g., "B", "b", "Hz"). Used
	// in short format strings and parsing. Can be empty.
	Symbol string
	// Singular is the full textual representation (e.g., "byte", "bit",
	// "hertz"). Used in long singular format strings and parsing. Can be empty.
	Singular string
	// Plural is the full textual representation for quantities other than 1
	// (e.g., "bytes", "bits", "hertz"). Used in long plural format strings and
	// parsing. Can be empty (often is if Singular == Plural, like "hertz"). If
	// Singular is empty, Plural may act as a suffix (e.g., custom time unit
	// "s").
	Plural string
}

Descriptor contains information about how a unit is represented textually

func Describe

func Describe(unit Unit) Descriptor

Describe returns the unit descriptor for the given unit.

func List

func List() []Descriptor

List returns information about all registered units

type FormatOption

type FormatOption func(*FormatOptions)

FormatOption represents a functional option for the Format function.

func Binary

func Binary() FormatOption

Binary configures the Format function to use IEC binary units (base-2). Units increase by powers of 1024 with prefixes like Ki, Mi, Gi.

func Decimal

func Decimal() FormatOption

Decimal configures the Format function to use SI decimal units (base-10). Units increase by powers of 1000 with prefixes like k, M, G.

func WithLongPrefix

func WithLongPrefix() FormatOption

WithLongPrefix uses the full name of unit prefixes instead of symbols.

Examples:

Format(1024, Binary(), WithLongPrefix())  // "1 kibi"
Format(1000, Decimal(), WithLongPrefix()) // "1 kilo"

func WithPlural

func WithPlural() FormatOption

WithPlural formats units using their plural names. This automatically uses long prefix formats.

Examples:

Format(1024, Binary(), WithUnit(Byte), WithPlural())  // "1 kibibytes"
Format(1000, Decimal(), WithUnit(Bit), WithPlural())  // "1 kilobits"

func WithPrecision

func WithPrecision(precision int) FormatOption

WithPrecision sets the number of decimal places to display.

Setting a negative precision will result in no decimal places.

Examples:

Format(1.5, WithPrecision(2))  // "1.50"
Format(1.5, WithPrecision(0))  // "2"

func WithSystem

func WithSystem(system *FormatSystem) FormatOption

WithSystem allows using a custom unit system for formatting

func WithSystemByName

func WithSystemByName(name string) FormatOption

WithSystemByName allows using a registered custom unit system by name

func WithUnit

func WithUnit(unit Unit) FormatOption

WithUnit specifies the unit type to use (Byte, Bit, Hz). This overrides any previous unit type settings. For built-in units, we also set appropriate format potentially overriding any previous format settings. For custom units, we don't change the format.

Examples:

Format(1024, Binary(), WithUnit(Byte))  // "1 KiB"
Format(1024, Binary(), WithUnit(Bit))   // "1 Kib"
Format(1000, Decimal(), WithUnit(Hz))   // "1 kHz"

func WithoutSpace

func WithoutSpace() FormatOption

WithoutSpace removes the space between the value and unit.

Examples:

Format(1024, Binary(), WithUnit(Byte), WithoutSpace())  // "1KiB"
Format(1000, Decimal(), WithUnit(Bit), WithoutSpace())  // "1kb"

type FormatOptions

type FormatOptions struct {
	Precision     int          // Number of decimal places (default: 0)
	UseSpace      bool         // Add space between value and unit (default: true)
	UsePluralUnit bool         // Use plural form of units (default: true)
	PrefixFormat  PrefixFormat // Format to use for unit prefixes (default: "short")
	FormatStyle   FormatStyle  // Format style to use for units (default: "decimal")
	Unit          Unit         // The unit to format with

	// Support for custom format systems
	Boundaries []float64          // Custom boundaries for unit scaling
	PrefixMap  map[float64]Prefix // Custom prefixes for unit formatting
	SystemName string             // Name of the formatting system
}

FormatOptions customizes the output of the formatting functions Note that UsePluralUnit implies using a long prefix format

type FormatStyle

type FormatStyle string

FormatStyle represents the format to use for units

const (
	DecimalFormat      FormatStyle = "decimal"      // k, kilo, M, mega, G, giga, T, tera, etc
	DecimalBytesFormat FormatStyle = "decimalBytes" // kB, kilobytes, MB, megabytes, GB, gigabytes, TB, terabytes, etc
	DecimalBitsFormat  FormatStyle = "decimalBits"  // b, bits, Kb, kilobits, Mb, megabits, Gb, gigabits, Tb, terabits, etc
	DecimalHertzFormat FormatStyle = "decimalHertz" // Hz, hertz, kHz, kilohertz, MHz, megahertz, GHz, gigahertz, THz, terahertz, etc
	BinaryFormat       FormatStyle = "binary"       // Ki, kibi, Mi, mebi, Gi, gibi, Ti, tebi, etc
	BinaryBytesFormat  FormatStyle = "binaryBytes"  // B, bytes, KiB, kibibytes, MiB, mebibytes, GiB, gibibytes, TiB, tebibytes, etc
	BinaryBitsFormat   FormatStyle = "binaryBits"   // b, bits, Kib, kibibits, Mib, mebibits, Gib, gibibits, Tib, tebibits, etc
)

type FormatSystem

type FormatSystem struct {
	// Name is the unique identifier for the format system, used for registration
	// and retrieval (e.g., via GetFormatSystem). Examples: "decimal", "binary", "time".
	Name string
	// Boundaries define the scaling thresholds for applying prefixes. It's a slice
	// of float64 values, typically sorted in descending order (e.g., [Mega, Kilo]
	// or [Mebi, Kibi]). A value is divided by the largest boundary it is
	// greater than or equal to during formatting.
	Boundaries []float64
	// Prefixes maps a boundary value (from the Boundaries slice) to its
	// corresponding Prefix definition (Name and Symbol). This map provides the
	// textual representation for each scaling level defined by the boundaries.
	// Example: {1000.0: {Name: "kilo", Symbol: "k"}, 1024.0: {Name: "kibi", Symbol: "Ki"}}
	Prefixes map[float64]Prefix
}

FormatSystem represents a system of units with associated boundaries

func GetFormatSystem

func GetFormatSystem(name string) (*FormatSystem, bool)

GetFormatSystem retrieves a registered format system by name

func MustRegisterFormatSystem

func MustRegisterFormatSystem(name string, boundaries []float64, prefixes map[float64]Prefix) *FormatSystem

MustRegisterFormatSystem is like RegisterFormatSystem but panics on error

func RegisterFormatSystem

func RegisterFormatSystem(name string, boundaries []float64, prefixes map[float64]Prefix) (*FormatSystem, error)

RegisterFormatSystem registers a new formatting system

type ParseError

type ParseError struct {
	Input string
	Msg   string
	Pos   int // position in input where error occurred
}

ParseError represents an error that occurred during parsing

func (*ParseError) Error

func (e *ParseError) Error() string

type ParseResult

type ParseResult struct {
	// Raw is the numeric value parsed directly from the input string, before
	// applying the prefix scale factor.
	Raw float64
	// Scale is the numeric scale factor determined by the parsed prefix (for
	// example, 1 for base unit, 1000 for Kilo, 1024 for Kibi).
	Scale float64
	// Unit is the base unit type identified (for example, Byte, Bit, Hertz, or
	// a custom unit). Will be None if only a number or number+prefix was
	// parsed.
	Unit Unit
}

ParseResult represents a parsed value with its unit

func MustParse

func MustParse(s string) ParseResult

MustParse is a convenience function that parses a string and panics if an error occurs.

func Parse

func Parse(s string) (ParseResult, error)

Parse attempts to parse a string containing a value with units. It handles standard and registered custom units and prefixes.

Examples of valid formats:

  • "1.5 KB" -> {Raw: 1.5, Scale: 1000, Unit: Byte}
  • "1 MiB" -> {Raw: 1, Scale: 1048576, Unit: Byte}
  • "500 MHz" -> {Raw: 500, Scale: 1000000, Unit: Hertz}
  • "2.7 kb" -> {Raw: 2.7, Scale: 1000, Unit: Bit}
  • "1024" -> {Raw: 1024, Scale: 1, Unit: None}

func (ParseResult) Format

func (r ParseResult) Format(opts ...FormatOption) Value

Format formats the value with the given options.

func (ParseResult) Value

func (r ParseResult) Value() float64

Convenience methods for Result

type Prefix

type Prefix struct {
	Name   string // Name is the name of the unit prefix, e.g. "kilo".
	Symbol string // Symbol is the short form of the unit symbol, e.g. "k".
}

Prefix represents a unit prefix.

func PrefixFor

func PrefixFor(value float64) Prefix

PrefixFor returns the prefix for a given value.

type PrefixFormat

type PrefixFormat string

PrefixFormat represents the format to use for unit prefixes

const (
	PrefixFormatShort PrefixFormat = "short" // k, M, G, T, Ki, Mi, Gi, Ti, etc
	PrefixFormatLong  PrefixFormat = "long"  // kilo, mega, giga, tera, kibi, mebi, gibi, tebi, etc
)

type Unit

type Unit int

Unit represents the type of unit.

const (
	None  Unit = iota // Raw number, no unit
	Byte              // Bytes (B)
	Bit               // Bits (b)
	Hertz             // Hertz (Hz)

)

func MustRegister

func MustRegister(descriptor Descriptor) Unit

MustRegister is like Register but panics on error

func Register

func Register(descriptor Descriptor) (Unit, error)

Register creates a new custom unit with the provided descriptor. It returns a Unit value that can be used with the formatting functions.

func (Unit) Info

func (u Unit) Info() Descriptor

Info returns information about a unit

func (Unit) String

func (u Unit) String() string

String returns the name of the unit (for stringer interface)

type Value

type Value struct {
	// Scaled is the numeric value after being adjusted (divided) by the
	// appropriate prefix scale (for example, Kilo, Mebi) selected during
	// formatting. The formatter chooses the prefix based on the magnitude of
	// the original value and the chosen format options (like Binary() or
	// Decimal()). For/ example, if the input was 1024 and Binary() format was
	// used, Scaled would be 1.0.
	Scaled float64

	// Prefix contains the details (Name and Symbol) of the unit prefix (like
	// "kilo", "k" or "Mebi", "Mi") that corresponds to the scaling factor
	// applied to the original value to get the Scaled value. If the original
	// value was too small to warrant a prefix, or if formatting options
	// disabled prefixes, this will be an empty Prefix struct (`{}`),
	// indicating the base unit scale (1.0) was used.
	Prefix Prefix

	// Unit holds the descriptive information (Symbol, Singular, Plural names)
	// for the fundamental base unit type (for example, Byte, Bit, Hertz, or a
	// custom registered unit). This descriptor is determined by the `WithUnit`
	// option passed to the formatting function or inferred from specific format
	// styles (like `DecimalBytesFormat`). It always represents the base unit,
	// not the combined prefix and unit (for example, it represents "byte", even
	// if the Prefix is "Kilo").
	Unit Descriptor
	// contains filtered or unexported fields
}

Value represents a formatted unit value.

func Format

func Format[T number](value T, opts ...FormatOption) Value

Format applies formatting options to a numeric value and returns the value. It handles both binary and decimal formatting with various unit types.

Examples:

// Basic formatting
Format(1024)                           // "1024"
Format(1024, Binary())                 // "1 Ki"
Format(1024, Binary(), WithUnit(Byte)) // "1 KiB"

// Combining multiple options
Format(1024, Binary(), WithUnit(Byte), WithPrecision(2))  // "1.00 KiB"
Format(1500, Decimal(), WithUnit(Bit), WithPlural())      // "1.5 kilobits"

// Advanced formatting
Format(1024, Binary(), WithUnit(Byte), WithoutSpace())    // "1KiB"
Format(1024, Binary(), WithUnit(Byte), WithLongPrefix())  // "1 kibibyte"

The first option that specifies a unit system (Binary/Decimal) takes precedence. If no unit system is specified, the default is Decimal.

func FormatBinary

func FormatBinary[T number](value T) Value

FormatBinary converts a numeric value to a human-readable string using IEC 80000-13 binary (base2) units. It picks the unit that converts to the smallest value and returns value and shorthand unit prefix. Examples of values: bytes, bits, hertz, etc.

Example:

FormatBinary(42)   // Value{Scaled: 42.0, Prefix: Prefix{}} -> String(): "42"
FormatBinary(1000) // Value{Scaled: 1000.0, Prefix: Prefix{}} -> String(): "1000"
FormatBinary(1024) // Value{Scaled: 1.0, Prefix: Prefix{Name: "kibi", Symbol: "Ki"}} -> String(): "1 Ki"

func FormatBinaryUnit

func FormatBinaryUnit[T number](value T, unit Unit) Value

FormatBinaryUnit converts a numeric value with an associated unit to a human-readable string using IEC 80000-13 binary (base2) units. It picks the unit that converts to the smallest value and returns the value and shorthand unit prefix.

Examples:

FormatBinaryUnit(42, Byte)    // Value{Scaled: 42.0, Prefix: Prefix{}, Unit: unit.Describe(Byte)} -> String(): "42 B"
FormatBinaryUnit(1000, Bit)   // Value{Scaled: 1000.0, Prefix: Prefix{}, Unit: unit.Describe(Bit)} -> String(): "1000 b"
FormatBinaryUnit(1024, Byte)  // Value{Scaled: 1.0, Prefix: unit.PrefixFor(Kibi), Unit: unit.Describe(Byte)} -> String(): "1 KiB"

Displaying file sizes in a human-readable way

fileSize := 1572864 // bytes
value := unit.FormatBinaryUnit(fileSize, unit.Byte)
fmt.Printf("File size: %s\n", value.String()) // Output: File size: 1.5 MiB

func FormatDecimal

func FormatDecimal[T number](value T) Value

FormatDecimal converts a numeric value to human-readable string using ISO 1000 metric (base10) SI units. It picks the unit that converts to the smallest value and returns the value and shorthand unit symbol. Examples of values: bytes, bits, hertz, etc.

Example:

FormatDecimal(42)      // Value{Scaled: 42.0, Prefix: Prefix{}} -> String(): "42"
FormatDecimal(1000)    // Value{Scaled: 1.0, Prefix: Prefix{Name: "kilo", Symbol: "k"}} -> String(): "1 k"
FormatDecimal(1024)    // Value{Scaled: 1.024, Prefix: Prefix{Name: "kilo", Symbol: "k"}} -> String(): "1 k" (due to default precision 0)

func FormatDecimalUnit

func FormatDecimalUnit[T number](value T, unit Unit) Value

FormatDecimalUnit converts a numeric value with an associated unit to a human-readable string using ISO 1000 metric (base10) SI units. It picks the unit that converts to the smallest value and returns the value and shorthand unit prefix.

Example:

FormatDecimalUnit(42, Byte)    // Value{Scaled: 42.0, Prefix: Prefix{}, Unit: unit.Describe(Byte)} -> String(): "42 B"
FormatDecimalUnit(1000, Bit)   // Value{Scaled: 1.0, Prefix: unit.PrefixFor(Kilo), Unit: unit.Describe(Bit)} -> String(): "1 kb"
FormatDecimalUnit(1024, Byte)  // Value{Scaled: 1.024, Prefix: unit.PrefixFor(Kilo), Unit: unit.Describe(Byte)} -> String(): "1 kB" (due to default precision 0)

Network bandwidth display

bandwidth := 1500000 // bits per second
value := unit.FormatDecimalUnit(bandwidth, unit.Bit)
fmt.Printf("Network speed: %s/s\n", value.String()) // Output: Network speed: 1.5 Mb/s

func (Value) Plural

func (u Value) Plural() string

Plural returns the plural form of the prefix and unit.

If unit singular is empty but has a plural suffix add the plural suffix to the prefix name, e.g., Prefix="hour", Unit={Singular:"", Plural:"s"} -> "hours".

If there's no prefix name, just use the unit's plural name, e.g. "bytes", "hertz".

Default: Combine prefix name and unit plural name, e.g. "kilo" + "bytes" -> "kilobytes".

Examples: kilobytes, kibibytes, megahertz

func (Value) Singular

func (u Value) Singular() string

Singular returns the singular form of the prefix and unit.

If unit singular is empty, the prefix name represents the whole unit, e.g., Prefix="hour", Unit={Singular:"", Plural:"s"} -> "hour".

If unit singular is empty and there's no prefix name, just use the unit's singular name, e.g. "byte", "hertz".

Default: Combine prefix name and unit singular name, e.g. "kilo" + "byte" -> "kilobyte".

Examples: kilobyte, kibibyte, megahertz

func (Value) String

func (u Value) String() string

String returns the formatted string representation of the unit value, fulfilling the fmt.Stringer interface.

The output format is determined by the FormatOptions that were used when this Value struct was created (typically via the Format function). It combines the Scaled numeric value (formatted according to the Precision option) with a textual representation of the combined prefix and unit.

Logic:

  1. The Scaled value is rounded and formatted to a string using the Precision specified in formatOptions.
  2. A combined prefix/unit string is generated based on formatOptions: - If UsePluralUnit is true, the Plural() method is called. - If UsePluralUnit is false: - If PrefixFormat is PrefixFormatShort, the Symbol() method is called. - If PrefixFormat is PrefixFormatLong, the Singular() method is called.
  3. If a non-empty prefix/unit string was generated: - A space is inserted between the formatted number and the prefix/unit string if UseSpace is true. - The formatted number, optional space, and prefix/unit string are concatenated.
  4. If no prefix/unit string was generated (e.g., formatting a raw number with no unit specified), only the formatted number string is returned.

Examples (assuming appropriate Value was generated by Format):

  • Value{Scaled: 1.5, Prefix: Kilo, Unit: Byte, opts: {Precision: 1, UsePluralUnit: true, UseSpace: true}} -> "1.5 kilobytes"
  • Value{Scaled: 1.5, Prefix: Kilo, Unit: Byte, opts: {Precision: 0, PrefixFormat: PrefixFormatShort, UseSpace: true}} -> "2 kB"
  • Value{Scaled: 1.5, Prefix: Kilo, Unit: Byte, opts: {Precision: 1, PrefixFormat: PrefixFormatLong, UseSpace: false}} -> "1.5kilobyte"
  • Value{Scaled: 1024, Prefix: {}, Unit: {}, opts: {}} -> "1024"

func (Value) Symbol

func (u Value) Symbol() string

Symbol returns the symbol form of the prefix and unit.

If unit symbol is empty, just use the prefix symbol, e.g., Prefix="h", Unit={Symbol:""} -> "h" .

If there's no prefix symbol, just use the unit symbol, e.g. "B", "Hz".

Default: Combine prefix symbol and unit symbol, e.g. "k" + "B" -> "kB".

Examples: kB, KiB, MHz

Jump to

Keyboard shortcuts

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