groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Alberto Vilches <vilc...@gmail.com>
Subject Re: Casting Double to BigDecimal
Date Mon, 11 Jan 2016 10:23:56 GMT
No, we are parsing a json with decimal numbers using the JSON.parse Grails
method. If we inspect these values with the IntelliJ IDEA debugger, the
json object has doubles. Then we return the value of some of them with a
method like this:

    BigDecimal getPeriodPrice(Integer period) {
        (pricePlan?.getAt(period) ?: 0.00)
    }

The pricePlan is an ArrayList of doubles. If we parse the "[1.9]" string as
JSON, the call to getPeriodPrice(0) returns a BigDecimal with "1.
899999999999999911182158029987476766109466552734375"

We fix the "bug" with:

    BigDecimal getPeriodPrice(Integer period) {
        (pricePlan?.getAt(period) ?: 0.00) as BigDecimal
    }

But we don't know why we have to do that because we thought the BigDecimal
in the method type do internally a "as BigDecimal" call. But what is
happening is just a cast, with a different result.

PS: trying to reproduce in the Groovy console using the JsonSlurper, it
doesn't fail. This is because the Groovy JsonSlurper creates BigDecimals,
and Grails JSON.parse() creates doubles!

On Fri, Jan 8, 2016 at 3:48 PM, Guillaume Laforge <glaforge@gmail.com>
wrote:

> Out of curiosity, in your code, you really do verbatim
> (Bigdecimal)1.9D or 1.9.D as BigDecimal?
> Or is the number value passed as a parameter?
> Because, you know that 1.9 is actually a BigDecimal already in Groovy,
> right?
>
> Guillaume
>
> On Fri, Jan 8, 2016 at 1:15 PM, Alberto Vilches <vilches@gmail.com> wrote:
> > Hi everybody! We have an issue in our application, and we realized these
> two
> > lines have differents results. We wonder why because we think it should
> > calls to the DefaultGroovyMethods.asType(Number self, Class<T> c). But it
> > seems only the explicit call to "as" finally calls to the asType and the
> > casting do a different thing (just a new BigDecimal(1.9D), but we wonder
> in
> > which part of Groovy is happening)
> >
> > (BigDecimal)1.9D  //
> "1.899999999999999911182158029987476766109466552734375"
> > ->
> > 1.9D as BigDecimal  // "1.9"
> >
> > In fact, we tried to put these two lines in the Groovy console and see
> the
> > AST in all the phases. But in all of them shows the same code:
> >
> >    public java.lang.Object run() {
> >         ((1.9) as java.math.BigDecimal)
> >         return ((1.9) as java.math.BigDecimal)
> >     }
> >
> > Somebody please could give some light? Thank you very much and happy new
> > year :)
> >
> > --
> > Un saludo.
> > Alberto Vilches
>
>
>
> --
> Guillaume Laforge
> Apache Groovy committer & PMC member
> Product Ninja & Advocate at Restlet
>
> Blog: http://glaforge.appspot.com/
> Social: @glaforge / Google+
>



-- 
Un saludo.
Alberto Vilches

Mime
View raw message