BAEL-821 New class that shows different rounding techniques. Updated POM.
This commit is contained in:
parent
4033449580
commit
6d407f88a3
@ -45,6 +45,12 @@
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.decimal4j</groupId>
|
||||
<artifactId>decimal4j</artifactId>
|
||||
<version>${decimal4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
@ -369,6 +375,7 @@
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<decimal4j.version>1.0.3</decimal4j.version>
|
||||
<commons-io.version>2.5</commons-io.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
|
38
core-java/src/main/java/com/baeldung/maths/Round.java
Normal file
38
core-java/src/main/java/com/baeldung/maths/Round.java
Normal file
@ -0,0 +1,38 @@
|
||||
package com.baeldung.maths;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.text.DecimalFormat;
|
||||
|
||||
import org.apache.commons.math3.util.Precision;
|
||||
import org.decimal4j.util.DoubleRounder;
|
||||
|
||||
public class Round {
|
||||
private static final double PI = 3.1415d;
|
||||
|
||||
public static void main (String args[]) {
|
||||
System.out.println("PI: " + PI);
|
||||
System.out.printf("Value with 3 digits after decimal point %.3f %n", PI);
|
||||
// OUTPUTS: Value with 3 digits after decimal point 3.142
|
||||
DecimalFormat df = new DecimalFormat("###.###");
|
||||
System.out.println(df.format(PI));
|
||||
System.out.println(round(PI, 3));
|
||||
System.out.println(roundOptional(PI, 3));
|
||||
System.out.println(Precision.round(PI, 3));
|
||||
System.out.println(DoubleRounder.round(PI, 3));
|
||||
}
|
||||
|
||||
public static double round(double value, int places) {
|
||||
if (places < 0) throw new IllegalArgumentException();
|
||||
|
||||
BigDecimal bd = new BigDecimal(value);
|
||||
bd = bd.setScale(places, RoundingMode.HALF_UP);
|
||||
return bd.doubleValue();
|
||||
}
|
||||
|
||||
public static double roundOptional(double value, int places) {
|
||||
double scale = Math.pow(10, places);
|
||||
double rounded = Math.round(value * scale) / scale;
|
||||
return rounded;
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user