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
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})`)
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.