Why does the % sign appear when I print a float? – getting help

Hi, I am on MacBook Pro M1 chipset laptop. As shown below, when I don’t use “\n”, I get “%” sign printed, but when I use “\n”, it prints without “%” .

chap3 % cat main.go
package main

import "fmt"

func main() {
	fmt.Printf("%g", 2.332)
}
chap3 % go run main.go
2.332%
chap3 % vim main.go
chap3 % cat main.go
package main

import "fmt"

func main() {
	fmt.Printf("%g\n", 2.332)
}
chap3 % go run main.go
2.332
chap3 % go version
go version go1.19.2 darwin/arm64

Am I doing something wrong or am I missing something?


Hi, please ignore the above question. % was inserted by zsh. When I switch to bash, I get the expected output.

bash-3.2$ go run main.go
2.332bash-3.2$ vim main.go
bash-3.2$ go run main.go
2.332
bash-3.2$

Hi, @pmu, welcome back to the forum!

This is a great question. As it turns out, as you’ve already found out when testing different shells, this is an artifact of using zsh. If a program does not insert the last newline, zsh will insert the percent sign as a signal to the user that the program has ended without a newline. Bash doesn’t do this.

this happens because fmt.Printf("%g", 2.332) A newline character is not included. For that, you have to use fmt.Printf("%g\n", 2.332),

I’m not familiar with shells other than bash, so it’s good to know that we should keep an eye out for issues like this that can be caused by other shells like zsh. Thanks for asking and posting an answer; Maybe if someone else has this problem in the future, you’ll save them some headaches!



1 like

Hi @skillian, thanks for the reply. You are right. I’ve updated here so that if anyone else has a similar problem, he can find the answer here.

Leave a Comment