github.com/searKing/golang/go@v1.2.117/format/multiple_prefix/multiple_prefix.go (about)

     1  // Copyright 2020 The searKing Author. 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 multiple_prefix
     6  
     7  import (
     8  	"fmt"
     9  	"math"
    10  	"strings"
    11  
    12  	math_ "github.com/searKing/golang/go/math"
    13  )
    14  
    15  // 计量单位,如k、M、G、T
    16  // base^power [symbol|name]
    17  type multiplePrefix struct {
    18  	base   int
    19  	power  int
    20  	name   string // symbol's full name
    21  	symbol string
    22  }
    23  
    24  func (dp multiplePrefix) FormatInt64(number int64, precision int) string {
    25  	return dp.FormatFloat(float64(number), precision)
    26  }
    27  
    28  func (dp multiplePrefix) FormatUint64(number uint64, precision int) string {
    29  	return dp.FormatFloat(float64(number), precision)
    30  }
    31  
    32  func (dp multiplePrefix) FormatFloat(number float64, precision int) string {
    33  	humanBase := dp.Factor()
    34  	humanNumber := number / humanBase
    35  	if precision >= 0 {
    36  		humanNumber = math_.TruncPrecision(humanNumber, precision)
    37  	}
    38  	return fmt.Sprintf("%g%s", humanNumber, dp)
    39  }
    40  
    41  // Factor return base^power
    42  func (dp multiplePrefix) Factor() float64 {
    43  	if dp.Base() == 10 {
    44  		return math.Pow10(dp.Power())
    45  	}
    46  	return math.Pow(float64(dp.Base()), float64(dp.Power()))
    47  }
    48  
    49  func (dp multiplePrefix) String() string {
    50  	return dp.Symbol()
    51  }
    52  
    53  func (dp multiplePrefix) Base() int {
    54  	return dp.base
    55  }
    56  
    57  func (dp multiplePrefix) Power() int {
    58  	return dp.power
    59  }
    60  
    61  func (dp multiplePrefix) Symbol() string {
    62  	return dp.symbol
    63  }
    64  
    65  func (dp multiplePrefix) Name() string {
    66  	return dp.name
    67  }
    68  
    69  func (dp multiplePrefix) matched(prefix string) bool {
    70  	return strings.Compare(dp.symbol, prefix) == 0 || strings.Compare(dp.name, prefix) == 0
    71  }