github.com/richardwilkes/toolbox@v1.121.0/txt/comma.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  package txt
    11  
    12  import (
    13  	"fmt"
    14  	"strings"
    15  
    16  	"golang.org/x/exp/constraints"
    17  )
    18  
    19  // Comma returns text version of the value that uses commas for every 3 orders of magnitude.
    20  func Comma[T constraints.Integer | constraints.Float](value T) string {
    21  	return CommaFromStringNum(fmt.Sprintf("%v", value))
    22  }
    23  
    24  // CommaFromStringNum returns a revised version of the numeric input string that uses commas for every 3 orders of
    25  // magnitude.
    26  func CommaFromStringNum(s string) string {
    27  	var buffer strings.Builder
    28  	if strings.HasPrefix(s, "-") {
    29  		buffer.WriteByte('-')
    30  		s = s[1:]
    31  	}
    32  	parts := strings.Split(s, ".")
    33  	i := 0
    34  	needComma := false
    35  	if len(parts[0])%3 != 0 {
    36  		i += len(parts[0]) % 3
    37  		buffer.WriteString(parts[0][:i])
    38  		needComma = true
    39  	}
    40  	for ; i < len(parts[0]); i += 3 {
    41  		if needComma {
    42  			buffer.WriteByte(',')
    43  		} else {
    44  			needComma = true
    45  		}
    46  		buffer.WriteString(parts[0][i : i+3])
    47  	}
    48  	if len(parts) > 1 {
    49  		buffer.Write([]byte{'.'})
    50  		buffer.WriteString(parts[1])
    51  	}
    52  	return buffer.String()
    53  }