20

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?

Croo
  • 1,301
  • 2
  • 13
  • 32

4 Answers4

22

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.

Community
  • 1
  • 1
bishop
  • 37,830
  • 11
  • 104
  • 139
  • 9
    Your second option won't result in floating point division though: it just converts the result of integer division to floating point. – James Henstridge Dec 14 '13 at 03:59
  • @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. – bishop Dec 14 '13 at 16:25
  • converting one of them (either the numerator or the denominator) is sufficient. – nishanthshanmugham Oct 25 '17 at 22:55
6

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.

Linear
  • 21,074
  • 4
  • 59
  • 70
0

The replies suggest versions of fmt.Printf("%f", float32(a)/float32(b)). I was sceptical about this for large values of a or b, as the individual conversions to float32 might overflow even if their quotient wouldn't.

However, testing this here, the golang compiler seems to be clever enough to make float32(a)/float32(b) "just work", and hence constructs like

f, _ := big.NewRat(a, b).Float32()

unnecessary in this case.

heiner
  • 598
  • 6
  • 11
-7

well you should cast your division result as float

Franck Ngako
  • 163
  • 6