diff options
Diffstat (limited to 'docs/content/en/functions/int.md')
-rw-r--r-- | docs/content/en/functions/int.md | 59 |
1 files changed, 30 insertions, 29 deletions
diff --git a/docs/content/en/functions/int.md b/docs/content/en/functions/int.md index 33888e117..1d91c9fdd 100644 --- a/docs/content/en/functions/int.md +++ b/docs/content/en/functions/int.md @@ -1,50 +1,51 @@ --- title: int -linktitle: int -description: Creates an `int` from the argument passed into the function. -date: 2017-02-01 -publishdate: 2017-02-01 -lastmod: 2017-02-01 +description: Casts a value to a decimal (base 10) integer. categories: [functions] menu: docs: - parent: "functions" -keywords: [strings,integers] + parent: functions +keywords: [cast,strings,integers] signature: ["int INPUT"] -workson: [] -hugoversion: relatedfuncs: [] -deprecated: false -aliases: [] --- -Useful for turning strings into numbers. +With a decimal (base 10) input: +```go-html-template +{{ int 11 }} → 11 (int) +{{ int "11" }} → 11 (int) + +{{ int 11.1 }} → 11 (int) +{{ int 11.9 }} → 11 (int) ``` -{{ int "123" }} → 123 + +With a binary (base 2) input: + +```go-html-template +{{ int 0b11 }} → 3 (int) +{{ int "0b11" }} → 3 (int) ``` -{{% note "Usage Note" %}} -If the input string is supposed to represent a decimal number, and if it has -leading 0's, then those 0's will have to be removed before passing the string -to the `int` function, else that string will be tried to be parsed as an octal -number representation. +With an octal (base 8) input (use either notation): -The [`strings.TrimLeft` function](/functions/strings.trimleft/) can be used for -this purpose. +```go-html-template +{{ int 011 }} → 9 (int) +{{ int "011" }} → 9 (int) -``` -{{ int ("0987" | strings.TrimLeft "0") }} -{{ int ("00987" | strings.TrimLeft "0") }} +{{ int 0o11 }} → 9 (int) +{{ int "0o11" }} → 9 (int) ``` -### Explanation +With a hexadecimal (base 16) input: -The `int` function eventually calls the `ParseInt` function from the Go library -`strconv`. +```go-html-template +{{ int 0x11 }} → 17 (int) +{{ int "0x11" }} → 17 (int) +``` -From its [documentation](https://golang.org/pkg/strconv/#ParseInt): +{{% note %}} +Values with a leading zero are octal (base 8). When casting a string representation of a decimal (base 10) number, remove leading zeros: -> the base is implied by the string's prefix: base 16 for "0x", base 8 for "0", -> and base 10 otherwise. +`{{ strings.TrimLeft "0" "0011" | int }} → 11` {{% /note %}} |