github.com/spi-ca/misc@v1.0.1/nums/digits.go (about) 1 package nums 2 3 import ( 4 "github.com/spi-ca/misc/strutil" 5 "strings" 6 ) 7 8 // SplitSignFromInt64 decomposes a signed integer with a sign and positive integer. 9 func SplitSignFromInt64(src int64) (sign bool, dst uint64) { 10 signedInteger := uint64(src) 11 sign = 1 == (signedInteger >> 63) 12 13 //Two's complement!! 14 if sign { 15 dst = 1 + (signedInteger ^ (1<<64 - 1)) 16 } else { 17 dst = signedInteger & (1<<63 - 1) 18 } 19 return 20 } 21 22 // MergeSignFromUInt64 composes a signed integer with a sign and positive integer. 23 func MergeSignFromUInt64(sign bool, src uint64) (dst int64) { 24 //Two's complement!! 25 if sign { 26 dst = -int64(src & (1<<63 - 1)) 27 } else { 28 dst = int64(src & (1<<63 - 1)) 29 } 30 return 31 } 32 33 // FractionalStringify is a formatting function for a fractional part number. 34 func FractionalStringify(fractional, fractionalLength int, showPoint bool) (formatted string) { 35 if fractionalLength == 0 { 36 return 37 } 38 var builder strings.Builder 39 40 partialFormatted := strutil.FormatIntToStringReversed(fractional) 41 if leftDigits := fractionalLength - len(partialFormatted); leftDigits < 0 { 42 builder.WriteString(partialFormatted[-leftDigits:]) 43 } else { 44 builder.WriteString(partialFormatted) 45 for ; leftDigits > 0; leftDigits-- { 46 builder.WriteByte('0') 47 } 48 } 49 50 if showPoint { 51 builder.WriteByte('.') 52 } 53 54 return strutil.Reverse(builder.String()) 55 }