github.com/searKing/golang/go@v1.2.117/format/multiple_prefix/decimal_format.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  	"strings"
     9  	"unicode"
    10  
    11  	strings_ "github.com/searKing/golang/go/strings"
    12  )
    13  
    14  func DecimalFormatInt(number int, precision int) string {
    15  	return DecimalFormatInt64(int64(number), precision)
    16  }
    17  
    18  func DecimalFormatUint(number uint, precision int) string {
    19  	return DecimalFormatUint64(uint64(number), precision)
    20  }
    21  
    22  func DecimalFormatInt64(number int64, precision int) string {
    23  	return DecimalMultiplePrefixTODO.Copy().SetInt64(number).FormatInt64(number, precision)
    24  }
    25  
    26  func DecimalFormatUint64(number uint64, precision int) string {
    27  	return DecimalMultiplePrefixTODO.Copy().SetUint64(number).FormatUint64(number, precision)
    28  }
    29  
    30  func DecimalFormatFloat(number float64, precision int) string {
    31  	return DecimalMultiplePrefixTODO.Copy().SetFloat64(number).FormatFloat(number, precision)
    32  }
    33  
    34  // SplitDecimal splits s into number, multiple_prefix and unparsed strings
    35  func SplitDecimal(s string) (number string, prefix *DecimalMultiplePrefix, unparsed string) {
    36  	splits := strings_.SplitPrefixNumber(s)
    37  	if len(splits) < 2 {
    38  		return "", nil, unparsed
    39  	}
    40  	number = splits[0]
    41  	// trim any space between numbers and symbols
    42  	unparsed = strings.TrimLeftFunc(splits[1], unicode.IsSpace)
    43  
    44  	for _, prefix := range decimalPositiveMultiplePrefixes {
    45  		if strings.HasPrefix(unparsed, prefix.Symbol()) {
    46  			return number, prefix.Copy(), strings.TrimPrefix(unparsed, prefix.Symbol())
    47  		}
    48  	}
    49  	for _, prefix := range decimalNegativeMultiplePrefixes {
    50  		if strings.HasPrefix(unparsed, prefix.Symbol()) {
    51  			return number, prefix.Copy(), strings.TrimPrefix(unparsed, prefix.Symbol())
    52  		}
    53  	}
    54  	for _, prefix := range decimalZeroMultiplePrefixes {
    55  		if strings.HasPrefix(unparsed, prefix.Symbol()) {
    56  			return number, prefix.Copy(), strings.TrimPrefix(unparsed, prefix.Symbol())
    57  		}
    58  	}
    59  	return number, nil, unparsed
    60  }