Alex
Alex

Reputation: 6099

Golang string formatting gives unexpected spacing

I have a line of code that looks like this:

fmt.Printf("Total Calories: %2.f (%2.f%%)\n", item.calorie.TotalCalories, item.calorie.TotalCalories/dailyCalorie*100)

It is supposed to output:

Total Calories: 150 (5%)

But instead I get a spacing between the start of the paranthesis and the number 5, like this:

Total Calories: 150 ( 5%)

I don't understand where I went wrong.

Upvotes: 0

Views: 172

Answers (1)

Alex Harris
Alex Harris

Reputation: 6392

%2.f is giving a default width of 2. You can try just %f.

Width is specified by an optional decimal number immediately preceding the verb. If absent, the width is whatever is necessary to represent the value. Precision is specified after the (optional) width by a period followed by a decimal number. If no period is present, a default precision is used. A period with no following number specifies a precision of zero. Examples:

%f     default width, default precision
%9f    width 9, default precision
%.2f   default width, precision 2
%9.2f  width 9, precision 2
%9.f   width 9, precision 0

You can read the documentation here.

Upvotes: 5

Related Questions