Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read float notation in golang?

Tags:

go

When printing out some values from a map of structs. I see certain float64 values with alternative notation. The test passes but how do you read this notation (4e-06). Is this value indeed 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
}
like image 765
user2108258 Avatar asked Dec 18 '16 20:12

user2108258


2 Answers

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

It has the form of

m × 10n

(m times ten raised to the power of n)

In programming languages it is written / printed as:

men

See Spec: Floating-point literals.

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

like image 74
icza Avatar answered Nov 15 '22 08:11

icza


In order to print your floats in a regular 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
like image 35
Chiheb Nexus Avatar answered Nov 15 '22 07:11

Chiheb Nexus