简体   繁体   中英

Wrong double to float precision loss with Groovy on Android

I am experiencing a problem which eventually is a bug. I am programming an Android app in Groovy on Android Studio. It gives me weird compilation errors with respect to the following code:

def foo(float s) {
    s = s / 2  // compilation error with pointer at '/' position
    s = s.toFloat() / 254  // no error
}

The compilation error occurs even if the first line within the function is swapped with the last line.

I also tried the code on my local Groovy 1.8.6 environment outside of Android Studio on the command line. It doesn't give any error.

Who can explain me this irregular behavior? Is this normal? Are there more clever ways to circumvent this? Should I send a bug ticket to Groovy?

I am using Android Studio 2.1.2 with Oracle JVM 1.8.0_92 and the following gradle dependencies:

classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'org.codehaus.groovy:gradle-groovy-android-plugin:0.3.10'
compile   'org.codehaus.groovy:groovy:2.4.6:grooid'

Edit : Here comes the compilation error from Android Studio:

/path/to/androidproject/Bar.groovy: 199: [Static type checking] - Possible loss of precision from double to float
@ line 199, column 19.
           s = s / 2
                 ^

Edit 2 : The following code compiles even on Android:

def foo(float s) {
    s = s * 2
}

Try:

s = s / 2.0f

or

s = (float) (s / 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM