castinggofloating-point-precision

How to count decimal places of float?


I want to check if a float32 has two decimal places or not. My javascript way to do this would look like:

step  := 0.01
value := 9.99

if int(value/step) % 1 == 0 {
    printf("has two decimal places!")
}

The above example also works. However it will not work when step is incorrect as go then cannot properly cast from float64 to int.

Example:

step  := 0.1
value := 9.99

if int(value/step) % 1 == 0 {
    printf("has two decimal places!")
}

Compiler Error: constant 9.99 truncated to integer

When we use dynamic values it will just return true for every case.

So what is the appropriate way to count decimal places?


Solution

  • int value % 1 is always zero!

    I suggest an alternative way:

    value := float32(9.99)
    valuef := value*100
    extra := valuef - float32(int(valuef))
    if extra < 1e-5 {
        fmt.Println("has two decimal places!");
    }
    

    http://play.golang.org/p/LQQ8T6SIY2

    Update

    package main
    
    import (
        "math"
    )
    
    func main() {
        value := float32(9.9990001)
    
        println(checkDecimalPlaces(3, value))
    }
    
    func checkDecimalPlaces(i int, value float32) bool {
        valuef := value * float32(math.Pow(10.0, float64(i)))
        println(valuef)
        extra := valuef - float32(int(valuef))
    
        return extra == 0
    }
    

    http://play.golang.org/p/jXRhHsCYL-