Java ScriptEngine fails for 'long' addition?
-
18-06-2021 - |
سؤال
I'm using the ScriptEngine to perform calculations specified in a String. I tried a simple program as below:
public static void main(String[] args){
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
Float f;
try {
f = new Float(engine.eval("1340984972921+7200000").toString());
System.out.println(f.longValue()+"");
} catch (Exception e){}
}
This gives the output of 1340992126976 but the correct answer is 1340992172921
This seems to work for reasonably large integers but fails for long values. I want them as long values because they are timestamps and I want to use them as such. Any ideas on what could make this work?
Thanks.
المحلول
Try changing the data type from Float
to Double
. I think it's a precision problem.
لا تنتمي إلى StackOverflow