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?