Home > Java > javaTutorial > How to Round Up a Double to 2 Decimal Places in Java?

How to Round Up a Double to 2 Decimal Places in Java?

DDD
Release: 2024-11-29 21:35:13
Original
225 people have browsed it

How to Round Up a Double to 2 Decimal Places in Java?

Round Up to 2 Decimal Places in Java

In Java, rounding up a double value to 2 decimal places can be achieved using the Math.round() method. However, simply multiplying and dividing the value by 100 doesn't always provide the desired results.

Solution:

The correct way to round up a double to 2 decimal places is to use Math.round() along with type casting to ensure that the operation calculates accurately:

In this code, we type cast the result of Math.round(a * 100.0) to a double to preserve the decimal precision. By multiplying a by 100.0, we effectively multiply it by 100, and then dividing it by 100.0 restores the decimal value.

The output of the above code for the given input a will be 123.14, which meets the requirement of rounding up to 2 decimal places.

The above is the detailed content of How to Round Up a Double to 2 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template