Use Strings for BigDecimal instantiation
io.github.timoa.misc.NormalizeBigDecimalCreation
Converts BigDecimal instantiation with a double literal to instantiation with a String.
CAUTION: This Recipe can change semantics.
When using doubles to instantiate BigDecimal objects it is not obvious what the result will be. new BigDecimal(0.1) for instance results in a value of 0.1000000000000000055511151231257827021181583404541015625 and a scale of 55. Other than rounding, the scale is also not transparent. While new BigDecimal("1.00") will have a value of 1.00 and a scale 2, neither new BigDecimal(1.00) nor BigDecimal.valueOf(1.00) will.
This recipe makes the assumption that a developer initializing a BigDecimal with the double some.digits really wants the object resulting from new BigDecimal("some.digit") but is not aware of the difference.
Usage
-
Maven POM
-
Maven Command Line
-
Gradle
-
Gradle init script
-
Add the following to your pom.xml file:
pom.xml<project> <build> <plugins> <plugin> <groupId>org.openrewrite.maven</groupId> <artifactId>rewrite-maven-plugin</artifactId> <version>6.12.1</version> <configuration> <activeRecipes> <recipe>io.github.timoa.misc.NormalizeBigDecimalCreation</recipe> </activeRecipes> </configuration> <dependencies> <dependency> <groupId>io.github.timo-a</groupId> <artifactId>rewrite-recipe-starter</artifactId> <version>0.4.2</version> </dependency> </dependencies> </plugin> </plugins> </build> </project> -
Run
mvn rewrite:runto run the recipe.
You will need to have Maven installed on your machine before you can run the following command.
mvn -U org.openrewrite.maven:rewrite-maven-plugin:run -Drewrite.recipeArtifactCoordinates=io.github.timo-a:rewrite-recipe-starter:RELEASE -Drewrite.activeRecipes=io.github.timoa.misc.NormalizeBigDecimalCreation
-
Add the following to your
build.gradlefile:build.gradleplugins { id("org.openrewrite.rewrite") version("7.9.0") } rewrite { activeRecipe("io.github.timoa.misc.NormalizeBigDecimalCreation") } repositories { mavenCentral() } dependencies { rewrite("io.github.timo-a:rewrite-recipe-starter:0.4.2") } -
Run
gradle rewriteRunto run the recipe.
-
Create a file named
init.gradlein the root of your project.init.gradleinitscript { repositories { maven { url "https://plugins.gradle.org/m2" } } dependencies { classpath("org.openrewrite:plugin:7.9.0") } } rootProject { plugins.apply(org.openrewrite.gradle.RewritePlugin) dependencies { rewrite("io.github.timo-a:rewrite-recipe-starter:0.4.2") } rewrite { activeRecipe("io.github.timoa.misc.NormalizeBigDecimalCreation") } afterEvaluate { if (repositories.isEmpty()) { repositories { mavenCentral() } } } } -
Run
gradle --init-script init.gradle rewriteRunto run the recipe.