github.com/huandu/go@v0.0.0-20151114150818-04e615e41150/doc/progs/eff_bytesize.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import "fmt"
     8  
     9  type ByteSize float64
    10  
    11  const (
    12  	_           = iota // ignore first value by assigning to blank identifier
    13  	KB ByteSize = 1 << (10 * iota)
    14  	MB
    15  	GB
    16  	TB
    17  	PB
    18  	EB
    19  	ZB
    20  	YB
    21  )
    22  
    23  func (b ByteSize) String() string {
    24  	switch {
    25  	case b >= YB:
    26  		return fmt.Sprintf("%.2fYB", b/YB)
    27  	case b >= ZB:
    28  		return fmt.Sprintf("%.2fZB", b/ZB)
    29  	case b >= EB:
    30  		return fmt.Sprintf("%.2fEB", b/EB)
    31  	case b >= PB:
    32  		return fmt.Sprintf("%.2fPB", b/PB)
    33  	case b >= TB:
    34  		return fmt.Sprintf("%.2fTB", b/TB)
    35  	case b >= GB:
    36  		return fmt.Sprintf("%.2fGB", b/GB)
    37  	case b >= MB:
    38  		return fmt.Sprintf("%.2fMB", b/MB)
    39  	case b >= KB:
    40  		return fmt.Sprintf("%.2fKB", b/KB)
    41  	}
    42  	return fmt.Sprintf("%.2fB", b)
    43  }
    44  
    45  func main() {
    46  	fmt.Println(YB, ByteSize(1e13))
    47  }