简体   繁体   中英

Round a number to 5 cents up in java

I'm trying to figure out how to round a monetary using this Rules:

 Tax calculated | Taxe imputed |
|---------------|--------------|
|          0.99 |         1.00 |
|          1.00 |         1.00 |
|          1.01 |         1.05 |
|          1.02 |         1.05 |

I tried various methods for rounding but always I get an error:

I have 2 books at 12.49€ with tax 10%; and one cd at 14.99€ with tax 20%

I tryied this method but always get false result

double number = 12.49 * 0.1 * 2;
double number2 = 14.99 * 0.2;
double round1 = Math.round(number * 100.0 /5.0) * 5.0 / 100.0;
double round2 = Math.round(number2 * 100.0 /5.0) * 5.0 / 100.0;

the console print 5.5 (round1+round2) but I should get 5.53

Help Please

  1. (double)Math.round(value * 100000d) / 100000d

    That's for 5 digits precision. The number of zeros indicate the number of decimals.

    please take a look at this (stack-overflow question) and this (oracle documentation)

     double round1 = Math.round(number * 100.0 /5.0) * 5.0 / 100.0; double round2 = Math.round(number2 * 100.0 /5.0) * 5.0 / 100.0;

    so , either you should reconsider the position of parenthesis (re-arrange the values) or please use another variable without round first and then do the round() operation.

    in this case simply,

     double round1 = Math.round(number * 1000.0 /5.0) * 5.0 / 1000.0; double round2 = Math.round(number2 * 1000.0 /5.0) * 5.0 / 1000.0;

    might solve the problem , but it is better to do it properly , so that it will remain meaningful later.

  2. Using Decimal format for string output , eg.,

     double val=8.888888; DecimalFormat df = new DecimalFormat("#.###");//for 3 decimal places df.setRoundingMode(RoundingMode.CEILING); String value=df.format(val);

    for more info check Class DecimalFormat , remember that it can be parsed to number , iff it is really necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM