Showing posts with label rounding-number. Show all posts
Showing posts with label rounding-number. Show all posts

Thursday, November 17, 2022

How to Drop Decimal Places Without Rounding, How to Round a Number to N Decimal Places in Java, Java – How to round double / float value to 2 decimal places, We can use DecimalFormat('0.00') or BigDecimal to round float / double to 2 decimal places.

So the problem is rounding number without rounding, for example we have a number 5.789 and if we want to keep 2 decimal places so that number would be 5.78, it's bit difficult. Because we have to use round number and the value would be 5.79 after rounding.
Below is a code snippet to drop decimal places without rounding:
public class NumberRounding {
    private static final DecimalFormat formatter = new DecimalFormat("#.####################");

    public static BigDecimal roundingAtFixedPrecision(Number number, Integer precision) {
        String[] parts = null;
        try {
            parts = formatter.format(number).split("\\.");

            if (parts.length == 1) {
                return new BigDecimal(parts[0]);
            }

            return new BigDecimal(parts[0] + "." + (parts[1].length() > precision ? parts[1].substring(0, precision) : parts[1]));
        }
        finally {
            number = null;
            precision = null;
            parts = null;
        }
    }
}
And output should be as below:

678.789 converted to 678.78
-39.9899 converted to -39.98
33 converted to 33
-40 converted to -40
3.9 converted to 3.9
9.009 converted to 9.00