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.
| Integer Division | Rounding Gotcha |
| Round | Rounding to a Multiple |
| Ceiling | Rounding Currency |
| Floor | Rounding to a Nickel |
| Truncate | Links |
| Cover |
// integer division // What percentage is "after" of "before" expressed as number 0..100 percent int percent = ( after * 100 ) / before; // truncated down int percent = ( after * 100 + before - 1) / before; // rounded up int percent = ( after * 100 + before/2) / before; // rounded
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;
On 2013-02-04 Canada discontinued the penny. Transactions are still computed to the penny, but are rounded to the nickel. The government has suggested (but not mandated) the following rounding rules.
The formula to compute the rounded amount could be described in words as.
You can calculate the rounded amount in a spreadsheet with =ROUNDDOWN((A1+2)/5)*5
The Canadian Sales Tax Calculator will compute the final sale amount including sales tax both penny and nickel-rounded.
|
|
available on the web at: |
http://mindprod.com/jgloss/round.html |
optional Replicator mirror
|
J:\mindprod\jgloss\round.html | |
![]() |
Please email your
feedback for publication,
letters to the editor, errors, omissions, typos, formatting errors, ambiguities, unclear
wording, broken/redirected link reports, suggestions to improve this page or comments to
Roedy Green :
| |
| Blog | Canadian
Mind
Products
IP:[65.110.21.43] Your face IP:[184.72.184.104] |
|
| Feedback | You are visitor number 135,465. | |