how can I force division to be floating point in Go?

11,420

Solution 1

There are no implicit type casts for variables in Go, so you must convert to float:

fmt.Printf("%f", float32(a)/float32(b))

or

fmt.Printf("%f", float32(a/b))

Depending upon what you want. Also check out float64 -- if that floats your boat.

Solution 2

You have to convert the types to floats first.

In general, if you have some non-float numeric types (such as ints) a and b, in order to get a float division you use float32(a)/ float32(b) (or float64 as the case may be). This applies to any other numeric type too, if you want to treat floats as integers or integers as complex numbers convert the operands. In this case, if a is 3 and b is 2, float32(a)/float32(b) will be 1.5.

If you want integer division to be done, but the result to be a float, then covert the result as in float32(a/b). In this case, if a is 3 and b is 2, then float32(a/b) will get you 1.0.

Share:
11,420

Related videos on Youtube

Croo
Author by

Croo

A developer.

Updated on June 25, 2022

Comments

  • Croo
    Croo about 2 years

    I have the following code snippet:

    package main
    
    import("fmt";"flag")
    
    func main() {
        var a = flag.Int("a",0,"divident")
        var b = flag.Int("b",1,"divisor")
        flag.Parse()
    
        fmt.Printf("%f",*a / *b )
    }
    

    For -a 3 and -b 2 command line arguments, the output is: %!f(int=1)

    What is the best / most elegant way to force this division to be floating point?

  • James Henstridge
    James Henstridge over 10 years
    Your second option won't result in floating point division though: it just converts the result of integer division to floating point.
  • bishop
    bishop over 10 years
    @JamesHenstridge: The OP read "force this division to be floating point". To me, that could read either way and actually reads integer divison to floating point. All that was known from the sample code was that the result of the division should be floating, to go into printf -- thus both ways were possible, thus I included both.
  • minerva
    minerva over 6 years
    converting one of them (either the numerator or the denominator) is sufficient.