Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding double in groovy

Tags:

groovy

I defined two doubles:

double abc1 = 0.0001;
double abc2 = 0.0001;

now if I print them:

println "Abc1 "+abc1;
println "Abc2 "+abc2;

it returns:

Abc1 1.0E-4

Abc2 1.0E-4

While if I add them:

println "Abc3 "+abc1+abc2;

It returns:

Abc3 1.0E-41.0E-4

rather than:

Abc3 2.0E-4

Why does this happen?

like image 880
Kamaldeep Singh Avatar asked Jan 17 '26 06:01

Kamaldeep Singh


1 Answers

This is because addition operator works from left to right and you start with string, hence the addition operator works as concatenation operator in your case.


This:

println "Abc3 "+abc1+abc2;

will be done step by step like this:

  1. println "Abc3 "+abc1+abc2;
  2. println "Abc3 1.0E-4"+abc2;
  3. println "Abc3 1.0E-41.0E-4";

Solution

If you want to get the result you are expecting, do it like this:

println "Abc3 " + (abc1 + abc2);

Here you are prioritizing the addition before the concatination.

like image 129
dsharew Avatar answered Jan 21 '26 09:01

dsharew