How to read floating symbols in golang?

When printing some values ​​from a structure map. I see some float64 values ​​with alternative notation. The test passes, but as you read this notation (4e-06). Is this value really the same as "0.000004"?

package main import ( "fmt" "strconv" "testing" ) func TestXxx(t *testing.T) { num := fmt.Sprintf("%f", float64(1.225788)-float64(1.225784)) // 0.000004 f, _ := strconv.ParseFloat(num, 64) if f == 0.000004 { t.Log("Success") } else { t.Error("Not Equal", num) } if getFloat(f) == 0.000004 { t.Log("Success") }else{ t.Error("Fail", getFloat(f)) } } func getFloat(f float64) float64 { fmt.Println("My Float:",f) // 4e-06 return f } 
+6
source share
3 answers

The designation is called Scientific Notation , and it is a convenient way to print very small or very large numbers in a compact, short form.

It has the form

m Γ— 10 n

(m times ten increased to degree n)

In programming languages, it is written / printed as:

t e p

See Spec: Floating Point Literals .

Your number: 4e-06 , where m=4 and n=-6 , which means 4*10 -6 which is equal to 0.000004 .

+5
source

To print your floats in the usual way, you can do something like this example:

 package main import ( "fmt" "strconv" ) func main() { a, _ := strconv.ParseFloat("0.000004", 64) b, _ := strconv.ParseFloat("0.0000000004", 64) c := fmt.Sprintf("10.0004") cc, _ := strconv.ParseFloat(c, 64) fmt.Printf("%.6f\n", a) // 6 numbers after the point fmt.Printf("%.10f\n", b) // 10 numbers afer the point fmt.Printf("%.4f\n", cc) // 4 numbers after the point } 

Output:

 0.000004 0.0000000004 10.0004 
+3
source

This is the same number. You can use fmt.Printf("My Float: %.6f\n",f) if you don't like scientific notation. (This format requires 6 digits to be printed after the decimal point.)

+1
source

Source: https://habr.com/ru/post/1013269/


All Articles