truncate decimal value in java

 Methid 1:

Truncate Decimal Value In Java Using BigDecimal

import java.math.BigDecimal;

public class TruncateDecimal {

public static void main(String[] args) {
double num = 21.288827938373635363383838;
System.out.println(“Before truncate=” + num);
System.out.println(“After Truncate=” + truncateDecimal(num, 3));
}

private static BigDecimal truncateDecimal(double x, int numberofDecimals) {
if (x > 0) {
return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals,
BigDecimal.ROUND_FLOOR);
} else {
return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals,
BigDecimal.ROUND_CEILING);
}
}

}

Output:

Before truncate=21.288827938373636
After Truncate=21.288

Method 2:

public class TruncateDecimal {

public static void main(String[] args) {
double num = 21.288827938373635363383838;
System.out.println(“Before truncate=” + num);
System.out.println(“After Truncate=” + truncateDecimalPlaces(num));
}

public static double  truncateDecimalPlaces(double num) {

// Get two decimal value of input valueToCheck
return (Math.floor(num * 100) / 100);

}

}

Output:

Before truncate=21.288827938373636
After Truncate=21.28

 

Leave a Reply

Your email address will not be published. Required fields are marked *

15 + = 22