Languages

Java - how to round a number to two decimal places?

0 points
Asked by:
Dirask Community
6810

Hi!

How to round the result so that there are always two places after the decimal point, e.g. 56.99? I tried to useĀ Math.round() but unfortunatelyĀ it doesn't work :(

1 answer
0 points
Answered by:
Dirask Community
6810

After a little research here is the solution I found:

Rounding floatĀ numbers is not super easy, and it takes some time to understand.Ā It's best to go over a lot of examples and write a few utils.

In general, the issue of floatsĀ is quite a broad topic in programming and computer science.Ā For beginners, I suggest not going into too much detail, as it may be a bit discouraged by the amount of information available on this topic.

Example 1 with Math.round -Ā multiplication and division

Here we have a rounding method and some examples of its use.Ā I suggest to copy this example and modify it to better understand the action.

public class RoundExample1 {

    public static void main(String[] args) {

        System.out.println(roundTo2DecimalPlace(56.990));  // 56.99
        System.out.println(roundTo2DecimalPlace(56.994));  // 56.99
        System.out.println(roundTo2DecimalPlace(56.995));  // 57.0
        System.out.println(roundTo2DecimalPlace(56.996));  // 57.0
        System.out.println(roundTo2DecimalPlace(56.999));  // 57.0
    }

    public static double roundTo2DecimalPlace(double value) {
        return Math.round(value * 100.0) / 100.0;
    }
}

Example 2 with BigDecimal

The precision is set to the second place after the opposite, so for the third example, 56.995 we get: 56.99 instead of 57.0

import java.math.BigDecimal;
import java.math.RoundingMode;

public class RoundExample2 {

    public static void main(String[] args) {

        System.out.println(round(56.990)); // 56.99
        System.out.println(round(56.991)); // 56.99
        System.out.println(round(56.995)); // 56.99
        System.out.println(round(56.996)); // 57.0
        System.out.println(round(56.999)); // 57.0
    }

    public static double round(double value) {
        int precision = 2;
        BigDecimal bigDecimal = new BigDecimal(value);
        bigDecimal = bigDecimal.setScale(precision, RoundingMode.HALF_UP);
        return bigDecimal.doubleValue();
    }
}
0 comments Add comment
Native Advertising
šŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ā¤ļøšŸ’» šŸ™‚

Join