0

I've written a task in gradle which increments my projects version number when a jar file is created.

I'm using a simple decimal version number with 3 decimal places for example: version '2.001'.

The code works by parsing the string value to a double, incrementing by 0.001 and replacing the string. When incrementing from a non-zero ended value, the code works fine. for example 2.001 is correctly increased to 2.002. But when I try to parse a zero ended value, for example 2.010, I get a weird error. When the value 2.010 is parsed in as a double by Double.parseDouble, the value is read as 2.010999999999999997.

The full code is below:

task increaseVersionCode {
  double versionCode = Double.parseDouble(version.toString())

  println versionCode
  versionCode += 0.001
  println versionCode
  println "version '$version'"
  println "version '" + versionCode + "'"

  String newBuildFile = buildFile.getText().replaceFirst("version '$version'","version '" + versionCode + "'")

  buildFile.setText(newBuildFile)
}

The result of the println when the version is version '2.010' is below:

2.0109999999999997
2.0119999999999996
version '2.0109999999999997'
version '2.0119999999999996'

Any ideas why this happens?

ToYonos
  • 16,469
  • 2
  • 54
  • 70
Sam
  • 1,234
  • 3
  • 17
  • 32

1 Answers1

1

For the explanation, take a look at this answer and this one too, it's all about internal representation.

For the solution, use BigDecimal

double a = 2.010 + 0.001;
System.out.println(a); 

BigDecimal b = BigDecimal.valueOf(2.010);
System.out.println(b.add(BigDecimal.valueOf(0.001))); 

Output :

2.0109999999999997
2.011
ToYonos
  • 16,469
  • 2
  • 54
  • 70