What is the correct way to convert a *big.Rat to a int32

1,486 views
Skip to first unread message

Anindya Chatterjee

unread,
May 16, 2014, 8:40:41 AM5/16/14
to golan...@googlegroups.com
I was porting a java library to go-lang. There I found a piece of java code as follows, for which I could not find any golang equivalent.

BigDecimal bd = new BigDecimal((String)value);
int i = bd != null ? bd.intValue() : Integer.MIN_VALUE;

The closest equivalent to BigDecimal is big.Rat in golang. But big.Rat does not have anything similar to BigDecimal.intValue() to convert to a int32 not even to a big.Int. So what is the best way to achieve the similar result of java's BigDecimal.intValue() in golang?

Ian Lance Taylor

unread,
May 16, 2014, 9:37:22 AM5/16/14
to Anindya Chatterjee, golang-nuts
If bd is not used later then it looks like you want strconv.ParseInt.
I don't know why the Java code bothers to use a BigDecimal.

To convert a big.Rat to int do something like
f, _ := r.Float64()
i := int(f)

Ian

Ben Hood

unread,
May 16, 2014, 2:45:10 PM5/16/14
to Anindya Chatterjee, golan...@googlegroups.com
Is inf.Dec an option for you?

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Anindya Chatterjee

unread,
May 16, 2014, 2:52:55 PM5/16/14
to golan...@googlegroups.com, Anindya Chatterjee
Thanks for the link, but I think I am stuck here again with the same problem. How to convert *Dec to int32? Unless you meant to take the route of :


It is more or less similar of using *big.Rat I guess. In case I am misunderstood, please rectify me.

Michael Jones

unread,
May 16, 2014, 2:58:24 PM5/16/14
to Ben Hood, golang-nuts, Anindya Chatterjee

You could simply do a big int divide of the rat's numerator by its denominator. That is the integer value...

Ben Hood

unread,
May 16, 2014, 7:16:46 PM5/16/14
to Anindya Chatterjee, golang-nuts
On Fri, May 16, 2014 at 7:52 PM, Anindya Chatterjee <anid...@gmail.com> wrote:
> Thanks for the link, but I think I am stuck here again with the same
> problem. How to convert *Dec to int32? Unless you meant to take the route of
> :
>
> func (x *Dec) UnscaledBig() *big.Int
>
>
> It is more or less similar of using *big.Rat I guess. In case I am
> misunderstood, please rectify me.

I'm not 100% sure this will solve your issue, but inf.Dec does expose
the Unscaled() function to return an int64:

http://godoc.org/speter.net/go/exp/math/dec/inf#Dec.Unscaled

As for your int32, you could narrow the int64 to an int32, but the
things might not be be the same, which might not be helpful in your
scenario.
Reply all
Reply to author
Forward
0 new messages