Math conventions to reduce boilerplate code.
Add Math Common to your Gradle build script:
repositories {
mavenCentral()
}
dependencies {
implementation("com.eriksencosta.math:common:0.3.0")
}If you're using Maven, add to your POM xml file:
<dependency>
<groupId>com.eriksencosta.math</groupId>
<artifactId>common</artifactId>
<version>0.3.0</version>
</dependency>The library provides the Rounding strategy to make rounding
easier:
1.25.round(1) // 1.3By default, the RoundingMode.HALF_EVEN is
used for rounding (it is the rounding logic commonly taught at school). If you want to use a different mode, create a
Rounding and use it:
import java.math.RoundingMode
val rounding = Rounding.to(2, RoundingMode.FLOOR)
rounding.round(1.257) // 1.25
rounding.round(1.253) // 1.25
// Alternatively:
1.257.round(rounding) // 1.25
1.253.round(rounding) // 1.25If you want to round the result of a calculation, use the overloaded round() method which accepts a function as
parameter:
Rounding.to(2).round { 3.14159 * 10.0.squared() } // 314.16Alternatively:
{ 3.14159 * 10.0.squared() }.round(2) // 314.16The extension functions squared and cubed are available for BigDecimal, Double, Float, Long, and Int:
2.squared() // 4
2.0.cubed() // 8.0Read the API documentation for further details.