As we have %d for int. What is the format specifier for boolean values?
Asked
Active
Viewed 8.9k times
124
Rene Knop
- 1,686
- 3
- 13
- 25
Anuj Verma
- 1,809
- 3
- 13
- 22
-
Try a code example: https://play.golang.org/p/RDGQEryOLP – KingRider Jul 20 '17 at 14:18
-
1Note that [`strconv.FormatBool(b)` is *much* faster](https://stackoverflow.com/questions/38552803/how-to-convert-a-bool-to-a-string-in-go) in case speed is important. – maerics Nov 11 '18 at 19:04
4 Answers
172
If you use fmt package, you need %t format syntax. See package's reference for details.
ffriend
- 26,152
- 13
- 86
- 128
-
31Also note that the %v format will print a reasonable default string for any value. – Evan Shaw Aug 14 '11 at 21:43
-
If I try to take input a boolean value; any value starting from 't' is true and any other value is false. – Anuj Verma Aug 21 '11 at 17:43
-
package main import fmt "fmt" func main(){ var flag bool fmt.Scanf("%t",&flag) fmt.Printf("%t",flag) } – Anuj Verma Aug 22 '11 at 14:30
-
1@Anuj Verma: When scanning input, `fmt.Scanf` had to deal somehow with any string you pass it. It can read values `true` and `false` correctly, and that's its main purpose. When it doesn't see neither `true`, nor `false` in the input, it goes another way: it takes only first character and returns `true` if it is 't' or `false` if it is anything else, i.g. not-'t'. Note, that the rest of the input is still available for scanning with other options. For example, try [such](http://pastebin.com/2EqrRFJg) code and check results with different inputs. – ffriend Aug 23 '11 at 16:08
18
Use %t to format a boolean as true or false.
Digvijay S
- 2,595
- 1
- 8
- 21
Nitin
- 441
- 4
- 5
-
3This is a the same answer, but shortened of the accepted one, remember that if you want to answer you should check when you can add something the post does not contains – xKobalt Jul 06 '20 at 08:16
16
%t is the answer for you.
package main
import "fmt"
func main() {
s := true
fmt.Printf("%t", s)
}
Unico
- 437
- 3
- 6
2
Some other options:
package main
import "strconv"
func main() {
s := strconv.FormatBool(true)
println(s == "true")
}
package main
import "fmt"
func main() {
var s string
// example 1
s = fmt.Sprint(true)
println(s == "true")
// example 2
s = fmt.Sprintf("%v", true)
println(s == "true")
}
Zombo
- 1
- 55
- 342
- 375