Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interpolate a number inside a string

Tags:

go

The following code

package main  import (     "fmt" )  func main() {     fmt.Println(say(9)) }  func say(num int)(total string){ return fmt.Sprintf("There are %s reasons to code!", num) } 

Produces the following output

There are %!s(int=9) reasons to code! 

My question

What should I do to interpolate a number inside a string?

like image 679
Stephen Nguyen Avatar asked Jan 30 '14 06:01

Stephen Nguyen


People also ask

How do you use string interpolation?

As the colon (":") has special meaning in an interpolation expression item, to use a conditional operator in an interpolation expression, enclose that expression in parentheses. string name = "Horace"; int age = 34; Console. WriteLine($"He asked, \"Is your name {name}?\

Can we use expressions Inside string interpolation?

The string interpolation result is 'Hello, World!' . You can put any expression inside the placeholder: either an operator, a function call, or even more complex expressions. ${n1 + n2} is a placeholder consisting of the addition operator and 2 operands.

What is meant by string interpolation?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

Can you do string interpolation in JavaScript?

String interpolation in JavaScript is a process in which an expression is inserted or placed in the string. To insert or embed this expression into the string a template literal is used. By using string interpolation in JavaScript, values like variables and mathematical expressions and calculations can also be added.


2 Answers

If you want to always use the "default" representation of no matter what type, use %v as in

fmt.Sprintf("There are %v reasons to code!", num) 
like image 83
metakeule Avatar answered Oct 02 '22 18:10

metakeule


Try %d instead of %s. The d stands for decimal.

The appropriate documentation is here:

http://golang.org/pkg/fmt/

like image 28
David Grayson Avatar answered Oct 02 '22 17:10

David Grayson