
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() {
fmt.Println(u.MustConvertFloat(25.5, u.Celsius, u.Fahrenheit))
val := u.NewValue(25.5, u.Celsius)
fmt.Println(val)
fmt.Println(val.MustConvert(u.Fahrenheit))
fmt.Println(val.MustConvert(u.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)
fmt.Println(val.MustConvert(u.Byte))
opts := u.FmtOptions{
Label: true,
Short: true,
Precision: 3,
}
val = u.NewValue(15.456932, u.KiloMeter)
fmt.Println(val)
fmt.Println(val.Fmt(opts))
fmt.Println(val.Float())
Lookup
The package-level Find()
method may be used to search for a unit by name, symbol, or alternate spelling:
unit, err := u.Find("m")
unit, err := u.Find("meter")
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:
Ding := u.NewUnit("ding", "di")
Dong := u.NewUnit("dong", "do")
u.NewRatioConversion(Ding, Dong, 100.0)
val := u.NewValue(25.0, Ding)
fmt.Printf("%s = %s\n", val, val.MustConvert(Dong))
KiloDong := u.Kilo(Dong)
fmt.Println(u.MustConvertFloat(1000.0, Dong, KiloDong))