Home > Java > javaTutorial > How to Correctly Round Doubles to Two Decimal Places in Java?

How to Correctly Round Doubles to Two Decimal Places in Java?

Mary-Kate Olsen
Release: 2024-11-30 07:35:16
Original
671 people have browsed it

How to Correctly Round Doubles to Two Decimal Places in Java?

Rounding to Two Decimal Places in Java

Many developers encounter challenges when attempting to round floating-point numbers to specific decimal places in Java. This is particularly true when the desired output must remain a double.

One common approach involves utilizing Math.round(), as demonstrated in the following code:

class Round {
    public static void main(String[] args) {

        double a = 123.13698;
        double roundOff = Math.round(a * 100) / 100;
        
        System.out.println(roundOff);
    }
}
Copy after login

However, this approach often fails to produce the desired result. Instead of rounding to 123.14, it outputs 123.

To rectify this issue, a slight modification to line 4 is required:

double roundOff = Math.round(a * 100.0) / 100.0;
Copy after login

By adding .0 to the multiplication factor, the result is cast to a double with two decimal places. This ensures that the final result also has two decimal places.

Alternatively, as suggested by @Rufein, one can cast the rounded value to a double:

double roundOff = (double) Math.round(a * 100) / 100;
Copy after login

This approach also effectively produces the desired output of 123.14 with two decimal places.

The above is the detailed content of How to Correctly Round Doubles to Two Decimal Places in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template