0

Let's say we have a converted float to a string:

"24.22334455667"

I want to just return 6 of the digits on the right of the decimal

I can get all digits, after the decimal this way:

re2 := regexp.MustCompile(`[!.]([\d]+)$`)

But I want only the first 6 digits after the decimal but this returns nothing:

re2 := regexp.MustCompile(`[!.]([\d]{1,6})$`)

How can I do this? I could not find an example of using [\d]{1,6}

Thanks

Slinky
  • 5,662
  • 14
  • 76
  • 130
  • 2
    I think, here better not use regex. Show this: http://stackoverflow.com/questions/18390266/how-can-we-truncate-float64-type-to-a-particular-precision-in-golang and then converting. –  Sep 13 '15 at 17:06

2 Answers2

4

Alternatively...

func DecimalPlaces(decimalStr string, places int) string {
    location := strings.Index(decimalStr, ".")
    if location == -1 {
        return ""
    }
    return decimalStr[location+1 : min(location+1+places, len(decimalStr))]
}

Where min is just a simple function to find the minimum of two integers.

Regular expressions seem a bit heavyweight for this sort of simple string manipulation.

Playground

Linear
  • 21,074
  • 4
  • 59
  • 70
3

You must remove the end of the line anchor $ since it won't be a line end after exactly 6 digits. For to capture exactly 6 digits, the quantifier must be

re2 := regexp.MustCompile(`[!.](\d{6})`)

Note that, this would also the digits which exists next to !. If you don't want this behaviour, you must remove the ! from the charcater class like

re2 := regexp.MustCompile(`[.](\d{6})`)

or

For to capture digits ranges from 1 to 6,

re2 := regexp.MustCompile(`[!.](\d{1,6})`)
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274