-2

I want to know if there a way to apply custom masking/format to string and get the output

number:= 12345678

I want to format my number to a specific format.

func formatNumber(number string) string {
   format:= 123-45 678
   // do something here to format number 
    return formatedNumber
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
NEEL PATEL
  • 11
  • 2
  • `fmt.Sprintf()` is something to look at here. It uses C-style format expressions which are quite old but are implemented by new programming languages every now and then (such as Go), so they are worth knowing how to use. Really need more info on what your "format" can be and means to help more. – Zyl Apr 05 '21 at 17:47

2 Answers2

1

There are a few misconceptions in your code sample. Numbers in a computer aren't formatted, but a string representation of a number can be. Example below.

func main() {
    n1 := 12345678                               // type = int
    fmt.Printf("type: %T, value: %d\n", n1, n1)  // outputs "type: int, value: 12345678"
    
    n2 := "12345678"                             // type = string
    fmt.Printf("type: %T, value: %s\n", n2, n2)  // outputs "type: string, value: 12345678"
}

See https://golang.org/pkg/fmt/ for where %T and %d and %s come from.

To format a number, I don't think you can get exactly what you want. A few options though:

Below gets you something like what you seem to want based on your question.

func main() {
    mynumber := 12345678
    mystring := fmt.Sprintf("%d", mynumber)
    myformattedstring := fmt.Sprintf("%s-%s %s", mystring[:3], mystring[3:5], mystring[5:])
    fmt.Println(myformattedstring)
}

Here is a playground with this code.

Frank Bryce
  • 8,076
  • 4
  • 38
  • 56
1

Use math to calculate a number for each position. Format those numbers using fmt.Sprintf:

func formatNumber(number string) string {
    return fmt.Sprintf("%03d-%02d %03d", 
         number/100000, (number%100000)/1000, 
         number%1000)
}

A feature of this answered compared to others is that it correctly handles numbers less than 10000000.