units

package module
v0.0.0-...-1ff9907 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2024 License: MIT Imports: 9 Imported by: 0

README

Disclaimer

Originally forked from https://github.com/bcicen/go-units but I've modified it to better suit my needs.

go-units

Go library for manipulating and converting between various units of measurement

Usage

In the most basic usage, go-units may be used to convert a value from one unit to another:

package main

import (
	"fmt"
	u "github.com/bcicen/go-units"
)

func main() {
	// convert a simple float from celsius to fahrenheit
	fmt.Println(u.MustConvertFloat(25.5, u.Celsius, u.Fahrenheit)) // outputs "77.9 fahrenheit"

	// convert a units.Value instance
	val := u.NewValue(25.5, u.Celsius)

	fmt.Println(val)                           // "25.5 celsius"
	fmt.Println(val.MustConvert(u.Fahrenheit)) // "77.9 fahrenheit"
	fmt.Println(val.MustConvert(u.Kelvin))     // "298.65 kelvin"
}

Formatting

Aside from unit conversions, go-units may also be used for generating human-readable unit labels, plural names, and symbols:

val := u.NewValue(2.0, u.Nibble)
fmt.Println(val)                     // "2 nibbles"
fmt.Println(val.MustConvert(u.Byte)) // "1 byte"

// value formatting options may also be specified:
opts := u.FmtOptions{
  Label:     true, // append unit name/symbol
  Short:     true, // use unit symbol
  Precision: 3,
}

val = u.NewValue(15.456932, u.KiloMeter)
fmt.Println(val)           // "15.456932 kilometers"
fmt.Println(val.Fmt(opts)) // "15.457 km"
fmt.Println(val.Float())   // "15.456932"

Lookup

The package-level Find() method may be used to search for a unit by name, symbol, or alternate spelling:

// symbol
unit, err := u.Find("m")
// name
unit, err := u.Find("meter")
// alternate spelling
unit, err := u.Find("metre")

Custom Units

go-units comes with 260 unit names and symbols builtin; however, new units and conversions can be easily added:

// register custom unit names
Ding := u.NewUnit("ding", "di")
Dong := u.NewUnit("dong", "do")

// there are 100 dongs in a ding
u.NewRatioConversion(Ding, Dong, 100.0)

val := u.NewValue(25.0, Ding)

fmt.Printf("%s = %s\n", val, val.MustConvert(Dong)) // "25 dings = 2500 dongs"

// conversions are automatically registered when using magnitude prefix helper methods
KiloDong := u.Kilo(Dong)
fmt.Println(u.MustConvertFloat(1000.0, Dong, KiloDong)) // "1 kilodong"

Documentation

Overview

Package units is a library for manipulating and converting between various units of measurement

Index

Constants

This section is empty.

Variables

View Source
var (
	Bi   = UnitOptionQuantity("bits")
	Data = UnitOptionQuantity("bytes")

	Byte      = NewUnit("byte", "B", Data)
	KiloByte  = NewUnit("kilobyte", "KB", Data)
	MegaByte  = NewUnit("megabyte", "MB", Data)
	GigaByte  = NewUnit("gigabyte", "GB", Data)
	TeraByte  = NewUnit("terabyte", "TB", Data)
	PetaByte  = NewUnit("petabyte", "PB", Data)
	ExaByte   = NewUnit("exabyte", "", Data)
	ZettaByte = NewUnit("zettabyte", "", Data)
	YottaByte = NewUnit("yottabyte", "", Data)

	Kibibyte = NewUnit("kibibyte", "KiB", Data, IEC)
	Mebibyte = NewUnit("mebibyte", "MiB", Data, IEC)
	Gibibyte = NewUnit("gibibyte", "GiB", Data, IEC)
	Tebibyte = NewUnit("tebibyte", "TiB", Data, IEC)
	Pebibyte = NewUnit("pebibyte", "PiB", Data, IEC)
	Exbibyte = NewUnit("exbibyte", "EiB", Data, IEC)
	Zebibyte = NewUnit("zebibyte", "ZiB", Data, IEC)
	Yobibyte = NewUnit("yobibyte", "YiB", Data, IEC)

	Bit     = NewUnit("bit", "b", Bi)
	KiloBit = Kilo(Bit)
	MegaBit = Mega(Bit)
	GigaBit = Giga(Bit)
	TeraBit = Tera(Bit)
	PetaBit = Peta(Bit)
	ExaBit  = Exa(Bit)

	Nibble = NewUnit("nibble", "", Data)
)
View Source
var (
	Energy = UnitOptionQuantity("energy")

	// metric
	Joule      = NewUnit("joule", "J", Energy)
	KiloJoule  = Kilo(Joule)
	MegaJoule  = Mega(Joule)
	GigaJoule  = Giga(Joule)
	TeraJoule  = Tera(Joule)
	PetaJoule  = Peta(Joule)
	ExaJoule   = Exa(Joule)
	ZettaJoule = Zetta(Joule)
	YottaJoule = Yotta(Joule)
	MilliJoule = Milli(Joule)
	MicroJoule = Micro(Joule)
	NanoJoule  = Nano(Joule)
	PicoJoule  = Pico(Joule)
	FemtoJoule = Femto(Joule)
	AttoJoule  = Atto(Joule)

	WattHour     = NewUnit("watt-hour", "Wh", Energy)
	KiloWattHour = Kilo(WattHour)
	GigaWattHour = Giga(WattHour)
	MegaWattHour = Mega(WattHour)
	TeraWattHour = Tera(WattHour)
	PetaWattHour = Peta(WattHour)

	// other
	ElectronVolt = NewUnit("electronvolt", "eV", Energy)
	Calorie      = NewUnit("calorie", "cal", Energy)
)
View Source
var (
	Length = UnitOptionQuantity("length")

	// metric
	Meter      = NewUnit("meter", "m", Length, SI, UnitOptionAliases("metre"))
	ExaMeter   = Exa(Meter)
	PetaMeter  = Peta(Meter)
	TeraMeter  = Tera(Meter)
	GigaMeter  = Giga(Meter)
	MegaMeter  = Mega(Meter)
	KiloMeter  = Kilo(Meter)
	HectoMeter = Hecto(Meter)
	DecaMeter  = Deca(Meter)
	DeciMeter  = Deci(Meter)
	CentiMeter = Centi(Meter)
	MilliMeter = Milli(Meter)
	MicroMeter = Micro(Meter)
	NanoMeter  = Nano(Meter)
	PicoMeter  = Pico(Meter)
	FemtoMeter = Femto(Meter)
	AttoMeter  = Atto(Meter)

	Angstrom = NewUnit("angstrom", "Å", Length, BI, UnitOptionPlural("angstroms"))
	Inch     = NewUnit("inch", "in", Length, BI, UnitOptionPlural("inches"))
	Foot     = NewUnit("foot", "ft", Length, BI, UnitOptionPlural("feet"))
	Yard     = NewUnit("yard", "yd", Length, BI)
	Mile     = NewUnit("mile", "mi", Length, BI)
	League   = NewUnit("league", "lea", Length, BI)
	Furlong  = NewUnit("furlong", "fur", Length, BI)
)
View Source
var (
	Mass = UnitOptionQuantity("mass")

	// metric
	Gram      = NewUnit("gram", "g", Mass, SI)
	ExaGram   = Exa(Gram)
	PetaGram  = Peta(Gram)
	TeraGram  = Tera(Gram)
	GigaGram  = Giga(Gram)
	MegaGram  = Mega(Gram)
	KiloGram  = Kilo(Gram)
	HectoGram = Hecto(Gram)
	DecaGram  = Deca(Gram)
	DeciGram  = Deci(Gram)
	CentiGram = Centi(Gram)
	MilliGram = Milli(Gram)
	MicroGram = Micro(Gram)
	NanoGram  = Nano(Gram)
	PicoGram  = Pico(Gram)
	FemtoGram = Femto(Gram)
	AttoGram  = Atto(Gram)

	// imperial
	Grain  = NewUnit("grain", "gr", Mass, BI)
	Drachm = NewUnit("drachm", "dr", Mass, BI)
	Ounce  = NewUnit("ounce", "oz", Mass, BI)
	Pound  = NewUnit("pound", "lb", Mass, BI)
	Stone  = NewUnit("stone", "st", Mass, BI)
	Ton    = NewUnit("ton", "t", Mass, BI)
	Slug   = NewUnit("slug", "", Mass, BI)
)
View Source
var (
	Power = UnitOptionQuantity("power")

	// metric
	Watt      = NewUnit("watt", "W", Power)
	KiloWatt  = Kilo(Watt)
	MegaWatt  = Mega(Watt)
	GigaWatt  = Giga(Watt)
	TeraWatt  = Tera(Watt)
	PetaWatt  = Peta(Watt)
	ExaWatt   = Exa(Watt)
	ZettaWatt = Zetta(Watt)
	YottaWatt = Yotta(Watt)
)
View Source
var (
	Pressure = UnitOptionQuantity("pressure")

	// SI unit metric
	Pascal      = NewUnit("pascal", "Pa", Pressure, SI)
	ExaPascal   = Exa(Pascal)
	PetaPascal  = Peta(Pascal)
	TeraPascal  = Tera(Pascal)
	GigaPascal  = Giga(Pascal)
	MegaPascal  = Mega(Pascal)
	KiloPascal  = Kilo(Pascal)
	HectoPascal = Hecto(Pascal)
	DecaPascal  = Deca(Pascal)
	DeciPascal  = Deci(Pascal)
	CentiPascal = Centi(Pascal)
	MilliPascal = Milli(Pascal)
	MicroPascal = Micro(Pascal)
	NanoPascal  = Nano(Pascal)
	PicoPascal  = Pico(Pascal)
	FemtoPascal = Femto(Pascal)
	AttoPascal  = Atto(Pascal)

	// Other
	At       = NewUnit("technical atmosphere", "at", Pressure, BI, UnitOptionPlural("technical atmospheres"))
	Atm      = NewUnit("standard atmosphere", "atm", Pressure, BI, UnitOptionPlural("standard atmospheres"))
	Bar      = NewUnit("bar", "bar", Pressure, BI, UnitOptionPlural("bars"))
	CentiBar = Centi(Bar)
	MilliBar = Milli(Bar)
	MicroBar = Micro(Bar)
	Barye    = NewUnit("barye", "Ba", Pressure, BI, UnitOptionPlural("baryes"))
	InH2O    = NewUnit("inch of Water Column", "inH2O", Pressure, BI)
	InHg     = NewUnit("inch of Mercury", "inHg", Pressure, BI)
	MH2O     = NewUnit("meter of Water Column", "mmH2O", Pressure, BI, UnitOptionPlural("meters of Water Column"))
	MmH2O    = Milli(MH2O)
	CmH2O    = Centi(MH2O)
	MHg      = NewUnit("meter of Mercury", "mmHg", Pressure, BI, UnitOptionPlural("meters of Mercury"))
	MmHg     = Milli(MHg)
	CmHg     = Centi(MHg)
	Newton   = NewUnit("newton per square meter", "N/m²", Pressure, BI)
	Psi      = NewUnit("pound-force per square inch", "psi", Pressure, BI)
	Torr     = NewUnit("torr", "Torr", Pressure, BI)
)
View Source
var (
	Temp = UnitOptionQuantity("temperature")

	Celsius    = NewUnit("celsius", "C", Temp, UnitOptionPlural("none"), SI)
	Fahrenheit = NewUnit("fahrenheit", "F", Temp, UnitOptionPlural("none"), US)
	Kelvin     = NewUnit("kelvin", "K", Temp, UnitOptionPlural("none"), SI)
)
View Source
var (
	Time = UnitOptionQuantity("time")

	Second      = NewUnit("second", "s", Time)
	ExaSecond   = Exa(Second)
	PetaSecond  = Peta(Second)
	TeraSecond  = Tera(Second)
	GigaSecond  = Giga(Second)
	MegaSecond  = Mega(Second)
	KiloSecond  = Kilo(Second)
	HectoSecond = Hecto(Second)
	DecaSecond  = Deca(Second)
	DeciSecond  = Deci(Second)
	CentiSecond = Centi(Second)
	MilliSecond = Milli(Second)
	MicroSecond = Micro(Second)
	NanoSecond  = Nano(Second)
	PicoSecond  = Pico(Second)
	FemtoSecond = Femto(Second)
	AttoSecond  = Atto(Second)

	Minute = NewUnit("minute", "min", Time)
	Hour   = NewUnit("hour", "hr", Time)
	Day    = NewUnit("day", "d", Time)
	Month  = NewUnit("month", "", Time)
	Year   = NewUnit("year", "yr", Time)

	Decade     = NewUnit("decade", "", Time)
	Century    = NewUnit("century", "", Time)
	Millennium = NewUnit("millennium", "", Time)

	// more esoteric time units
	PlanckTime = NewUnit("planck time", "𝑡ₚ", Time)
	Fortnight  = NewUnit("fortnight", "", Time)
	Score      = NewUnit("score", "", Time)
)
View Source
var (
	// Shorthand for pre-defined unit systems
	BI  = UnitOptionSystem("imperial")
	SI  = UnitOptionSystem("metric")
	US  = UnitOptionSystem("us")
	IEC = UnitOptionSystem("iec")
)
View Source
var (
	Volume = UnitOptionQuantity("volume")

	// metric
	Liter      = NewUnit("liter", "l", Volume, SI, UnitOptionAliases("litre"))
	ExaLiter   = Exa(Liter)
	PetaLiter  = Peta(Liter)
	TeraLiter  = Tera(Liter)
	GigaLiter  = Giga(Liter)
	MegaLiter  = Mega(Liter)
	KiloLiter  = Kilo(Liter)
	HectoLiter = Hecto(Liter)
	DecaLiter  = Deca(Liter)
	DeciLiter  = Deci(Liter)
	CentiLiter = Centi(Liter)
	MilliLiter = Milli(Liter)
	MicroLiter = Micro(Liter)
	NanoLiter  = Nano(Liter)
	PicoLiter  = Pico(Liter)
	FemtoLiter = Femto(Liter)
	AttoLiter  = Atto(Liter)

	// imperial
	ImpQuart      = NewUnit("imperial quart", "imp qt", Volume, BI)
	ImpPint       = NewUnit("imperial pint", "imp pt", Volume, BI)
	ImpGallon     = NewUnit("imperial gallon", "imp gal", Volume, BI)
	ImpFluidOunce = NewUnit("imperial fluid ounce", "imp fl oz", Volume, BI)
	ImpTeaspoon   = NewUnit("imperial teaspoon", "imp tsp", Volume, BI, UnitOptionAliases("t"))
	ImpTablespoon = NewUnit("imperial tablespoon", "imp tbsp", Volume, BI, UnitOptionAliases("T"))
	ImpCup        = NewUnit("imperial cup", "imp c", Volume, BI)

	// US
	Quart      = NewUnit("quart", "qt", Volume, US)
	Pint       = NewUnit("pint", "pt", Volume, US)
	Gallon     = NewUnit("gallon", "gal", Volume, US)
	FluidOunce = NewUnit("fluid ounce", "fl oz", Volume, US, UnitOptionAliases("floz"))
	Teaspoon   = NewUnit("teaspoon", "tsp", Volume, US, UnitOptionAliases("t"))
	Tablespoon = NewUnit("tablespoon", "tbsp", Volume, US, UnitOptionAliases("T"))
	Cup        = NewUnit("cup", "c", Volume, US, UnitOptionAliases("C"))
)
View Source
var DefaultFmtOptions = FmtOptions{true, false, 6}

Functions

func NewConversion

func NewConversion(from, to Unit, formula string)

NewConversion registers a new conversion formula from one Unit to another

func NewConversionFromFn

func NewConversionFromFn(from, to Unit, f ConversionFn, formula string)

NewConversion registers a new conversion formula from one Unit to another

func NewRatioConversion

func NewRatioConversion(from, to Unit, ratio float64)

Register a conversion formula and the inverse, given a ratio of from Unit in to Unit

Types

type Conversion

type Conversion struct {
	Fn      ConversionFn
	Formula string
	// contains filtered or unexported fields
}

func ResolveConversion

func ResolveConversion(from, to Unit) (cpath []Conversion, err error)

ResolveConversion resolves a path of one or more Conversions between two units

func (Conversion) From

func (c Conversion) From() string

func (Conversion) String

func (c Conversion) String() string

String representation of conversion formula

func (Conversion) To

func (c Conversion) To() string

Conversion implements bfstree.Edge interface

type ConversionFn

type ConversionFn func(float64) float64

type FmtOptions

type FmtOptions struct {
	Label     bool // if false, unit label/symbol will be omitted
	Short     bool // if true, use unit shortname or symbol
	Precision int  // maximum meaningful precision to truncate value
}

type Unit

type Unit struct {
	Name     string
	Symbol   string
	Quantity string
	// contains filtered or unexported fields
}

func All

func All() []Unit

Return all registered Units, sorted by name and quantity

func Atto

func Atto(b Unit, o ...UnitOption) Unit

func Centi

func Centi(b Unit, o ...UnitOption) Unit

func Deca

func Deca(b Unit, o ...UnitOption) Unit

func Deci

func Deci(b Unit, o ...UnitOption) Unit

func Exa

func Exa(b Unit, o ...UnitOption) Unit

func Femto

func Femto(b Unit, o ...UnitOption) Unit

func Find

func Find(s string) (Unit, error)

Find Unit matching name or symbol provided

func Giga

func Giga(b Unit, o ...UnitOption) Unit

func Hecto

func Hecto(b Unit, o ...UnitOption) Unit

func Kilo

func Kilo(b Unit, o ...UnitOption) Unit

func Mega

func Mega(b Unit, o ...UnitOption) Unit

func Micro

func Micro(b Unit, o ...UnitOption) Unit

func Milli

func Milli(b Unit, o ...UnitOption) Unit

func Nano

func Nano(b Unit, o ...UnitOption) Unit

func NewUnit

func NewUnit(name, symbol string, opts ...UnitOption) Unit

NewUnit registers a new Unit within the package, returning the newly created Unit

func Peta

func Peta(b Unit, o ...UnitOption) Unit

func Pico

func Pico(b Unit, o ...UnitOption) Unit

func Quecto

func Quecto(b Unit, o ...UnitOption) Unit

func Quetta

func Quetta(b Unit, o ...UnitOption) Unit

Magnitude prefix methods create and return a new Unit, while automatically registering conversions to and from the provided base Unit

func Ronna

func Ronna(b Unit, o ...UnitOption) Unit

func Ronto

func Ronto(b Unit, o ...UnitOption) Unit

func Tera

func Tera(b Unit, o ...UnitOption) Unit

func Yocto

func Yocto(b Unit, o ...UnitOption) Unit

func Yotta

func Yotta(b Unit, o ...UnitOption) Unit

func Zepto

func Zepto(b Unit, o ...UnitOption) Unit

func Zetta

func Zetta(b Unit, o ...UnitOption) Unit

func (Unit) Names

func (u Unit) Names() []string

Returns all names and symbols this unit may be referred to

func (Unit) PluralName

func (u Unit) PluralName() string

Return the plural name for this unit

func (Unit) System

func (u Unit) System() string

Return the system of units this Unit belongs to, if any

type UnitList

type UnitList []Unit

func (UnitList) Len

func (a UnitList) Len() int

UnitList implements sort.Interface

func (UnitList) Less

func (a UnitList) Less(i, j int) bool

func (UnitList) Swap

func (a UnitList) Swap(i, j int)

type UnitOption

type UnitOption func(Unit) Unit

Option that may be passed to NewUnit

func UnitOptionAliases

func UnitOptionAliases(a ...string) UnitOption

Additional names, spellings, or symbols that this unit may be referred to as

func UnitOptionPlural

func UnitOptionPlural(s string) UnitOption

Either "none", "auto", or a custom plural unit name "none" - labels will use the unmodified unit name in a plural context "auto" - labels for this unit will be created with a plural suffix when appropriate (default)

func UnitOptionQuantity

func UnitOptionQuantity(s string) UnitOption

Set a quantity label for which this Unit belongs

func UnitOptionSystem

func UnitOptionSystem(s string) UnitOption

Set a system of units for which this Unit belongs

type Value

type Value struct {
	// contains filtered or unexported fields
}

func ConvertFloat

func ConvertFloat(x float64, from, to Unit) (Value, error)

ConvertFloat converts a provided float from one Unit to another

func MustConvertFloat

func MustConvertFloat(x float64, from, to Unit) Value

MustConvertFloat converts a provided float from one Unit to another, panicking on error

func NewValue

func NewValue(v float64, u Unit) Value

NewValue creates a new Value instance

func (Value) Convert

func (v Value) Convert(to Unit) (Value, error)

Convert converts this Value to another Unit

func (Value) Float

func (v Value) Float() float64

func (Value) Fmt

func (v Value) Fmt(opts FmtOptions) string

func (Value) MustConvert

func (v Value) MustConvert(to Unit) Value

MustConvert converts this Value to another Unit, panicking on error

func (Value) String

func (v Value) String() string

func (Value) Unit

func (v Value) Unit() Unit

Jump to

Keyboard shortcuts

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