Suppose I have an array with 2 items whose type is string / float. How should I print them together without scientific notation for float item.
For example:
package main
import (
"fmt"
)
func main() {
values := []interface{}{"mydata", 1234567890.123}
for _, v := range values{
fmt.Printf("%v
", v)
}
}
The output will be
mydata
1.234567890123e+09
What I want is
mydata
1234567890.123
The package doc of fmt
explains it: The %v
verb is the default format, which for floating numbers means / reverts to %g
which is
%e for large exponents, %f otherwise. Precision is discussed below.
If you always want "decimal point but no exponent, e.g. 123.456", use %f
explicitly.
But you can only use that for floating numbers, so you have to check the type of the value you print. For that you may use a type switch or type assertion.
Example:
switch v.(type) {
case float64, float32:
fmt.Printf("%f
", v)
default:
fmt.Printf("%v
", v)
}
Output (try it on the Go Playground):
mydata
1234567890.123000
You can use %f
to print a float. Given your slice of interfaces, you first need to check the type of the element. You can do so as follows:
package main
import (
"fmt"
)
func main() {
values := []interface{}{"mydata", 1234567890.123}
for _, v := range values {
// Check if the type conversion to float64 succeeds.
if f, ok := v.(float64); ok {
fmt.Printf("%f
", f)
} else {
fmt.Println(v)
}
}
}
Outputs:
mydata
1234567890.123000
The full list of flags for floats from fmt is:
%b decimalless scientific notation with exponent a power of two,
in the manner of strconv.FormatFloat with the 'b' format,
e.g. -123456p-78
%e scientific notation, e.g. -1.234456e+78
%E scientific notation, e.g. -1.234456E+78
%f decimal point but no exponent, e.g. 123.456
%F synonym for %f
%g %e for large exponents, %f otherwise. Precision is discussed below.
%G %E for large exponents, %F otherwise