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

4

25

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?

Pinfold answered 13/12, 2013 at 16:28 Comment(0)
K
27

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.

Ketubim answered 13/12, 2013 at 16:40 Comment(3)
Your second option won't result in floating point division though: it just converts the result of integer division to floating point.Earthworm
@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.Ketubim
converting one of them (either the numerator or the denominator) is sufficient.Vagrant
D
9

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.

Drover answered 13/12, 2013 at 16:34 Comment(0)
H
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.

Homesteader answered 10/2, 2023 at 14:27 Comment(0)
K
-10

well you should cast your division result as float

Kalbli answered 13/12, 2013 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.