jLibrary

How to Round a Number to N Decimal Places in Java

。_饼干妹妹 提交于 2020-02-28 11:10:51
1. Overview In this short article, we're going to look at how to round a number to n decimal places in Java. 2. Decimal Numbers in Java Java provides two primitive types that can be used for storing decimal numbers: float and double . Double is the type used by default: 1 double PI = 3.1415 ; However, both types should never be used for precise values , such as currencies. For that, and also for rounding, we can use the BigDecimal class. 3. Formatting a Decimal Number If we just want to print a decimal number with n digits after decimal point, we can simply format the output String: 1 2 System