size
dstgo/size is a convenient library for converting between strings and file sizes.
Repository: dstgo/size: Fast conversion between file size and string (github.com)
Documentation: dstgo/size: Fast conversion between file size and string (github.com)
Installation
$ go get https://github.com/dstgo/sizeUsage
go
const (
B Size = 1
KB = B * 1024
MB = KB * 1024
GB = MB * 1024
TB = GB * 1024
PB = TB * 1024
)go
type SizeMeta struct {
Data float64
Unit Size
}This library is very simple to use, with only two exposed functions:
go
func ParseSize(str string) SizeMetaParseSize converts a string into a SizeMeta struct, storing the data size and unit.
go
func ParseTargetSize(str string, size Size) SizeMetaParseTargetSize converts a string into a SizeMeta of the specified size.
Example:
go
package main
import (
"fmt"
"github.com/dstgo/size"
)
func main() {
parseSize := size.ParseSize("1.2MB")
fmt.Printf("%+v\n", parseSize)
fmt.Printf("%+v\n", parseSize.Round(1))
parseSize1 := size.ParseSize("2.3-asdajl")
fmt.Printf("%+v\n", parseSize1)
targetSize := size.ParseTargetSize("2.65MB", size.KB)
fmt.Printf("%+v", targetSize)
fmt.Printf("%+v", targetSize.String())
}After conversion, you can use the Round method to modify the number of decimal places to retain, or use the String method to get its string representation. Example output:
1.20MB
1.2
2713.60KB