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\n", v)     } }   The output will be
mydata
1.234567890123e+09
What I want is
mydata
1234567890.123
We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.
Within a given f-string, you can use the {...:f} format specifier to tell Python to use floating point notation for the number preceding the :f suffix. Thus, to print the number my_float = 0.00001 non-scientifically, use the expression print(f'{my_float:f}') .
Summary: Use the string literal syntax f"{number:. nf}" to suppress the scientific notation of a number to its floating-point representation.
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\n", v) default:     fmt.Printf("%v\n", 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\n", 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 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With