DecimalFormat automatically rounds output to the displayed number of decimal places, so there is nothing to do if you are rounding simply to make output look pretty.
| Round | Rounding Gotcha |
| Ceiling | Rounding to a Multiple |
| Floor | Rounding Currency |
| Truncate | Links |
| Cover |
long Math.round( double ); int Math.round( float ); double Math.rint( double ); // rounding to two decimal places double roundedValue = Math.rint( value * 100.0d ) / 100.0d;
| value | round |
|---|---|
| -1.6 | -2 |
| -1.5 | -2 |
| -1.4 | -1 |
| +1.4 | +1 |
| +1.5 | +2 |
| +1.6 | +2 |
double Math.ceil( double );See the description of covered quotient division.
| value | ceil |
|---|---|
| -1.6 | -1 |
| -1.5 | -1 |
| -1.4 | -1 |
| +1.4 | +2 |
| +1.5 | +2 |
| +1.6 | +2 |
double Math.floor( double );See floored division.
| value | floor |
|---|---|
| -1.6 | -2 |
| -1.5 | -2 |
| -1.4 | -2 |
| +1.4 | +1 |
| +1.5 | +1 |
| +1.6 | +1 |
int i = (int)d;
| value | truncate |
|---|---|
| -1.6 | -1 |
| -1.5 | -1 |
| -1.4 | -1 |
| +1.4 | +1 |
| +1.5 | +1 |
| +1.6 | +1 |
d < 0 ? Math.floor( d ) : Math.ceil( d );
| value | cover |
|---|---|
| -1.6 | -2 |
| -1.5 | -2 |
| -1.4 | -2 |
| +1.4 | +2 |
| +1.5 | +2 |
| +1.6 | +2 |
// rounding m up to next highest multiple of n int ceil = ( m + n - 1 ) / n * n; // rounding m down to multiple of n int floor = m / n * n; // rounding m to nearest multiple of n int near = ( m + n/2 ) / n * n;
| You can get the freshest copy of this page from: | or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror) | |
| http://mindprod.com/jgloss/round.html | J:\mindprod\jgloss\round.html | |
![]() | ||
| Canadian Mind Products | ||
| mindprod.com IP:[65.110.21.43] | ||
| view Blog | Your face IP:[38.107.191.107] | |
| Feedback | You are visitor number 88,497. | |