Why does a % sign show up when I print a float?

Hi, I am on a MacBook Pro M1 chipset laptop. As shown below, I get a “%” sign printed when I do not use “\n”, but when I do use “\n”, It prints without the “%”.

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 missing something?

Hi, Please ignore the above question. The % was inserted by zsh. When I switch over 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, like you have already found when testing different shells, this is an artifact of using zsh. If a program does not insert a final newline, zsh will insert the percent sign as a signal to the user that the program ended without a newline. bash doesn’t do that.

This happens because fmt.Printf("%g", 2.332) does not include a new line character. 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 may be caused by other shells like zsh. Thanks for asking and for posting the answer; maybe if someone else has this issue in the future, you’ll save them some headache!

2 Likes

Hi @skillian , Thank you for the reply. You are right. I updated here so if someone else has a similar issue, he can get the answer here.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.