2

I'm new to java programming. I would like to round up a price to the nearest 2 decimal places with a multiple of 5.

Eg.

  • 38.80 stays the same.
  • 38.81 to 38.80.
  • 38.82 to 38.80.
  • 38.83 to 38.85.
  • 38.84 to 38.85.
  • 38.85 stays the same.
  • 38.86 to 38.85.
  • 38.87 to 38.85.
  • 38.88 to 38.90.
  • 38.89 to 38.90.
  • 38.90 stays the same.

I tried the provided duplicates but they come out only to 1 decimal place. Eg. 38.82 to 38.8.

This is my code:

import java.text.DecimalFormat;

public class RoundUp {

    public static void main(String[] args){
        DecimalFormat df = new DecimalFormat("#.##");
        double num = 38.84;
        System.out.println(df.format(Math.round(num*10.00)/10.00));
    }
}

I have looked into other model answers by experts in this web but none of them really answer my question. Setting into 2 decimal places, I'm using DemicalFormat. That I know, but rounding the number, let's say 38.83 to 38.85 and 38.87 to 38.90 is what I really want. It is a rounding system that my country is using. Can check it out here.

**

This question has been answer by @Mureinik double rounded = Math.round(num * 100.0 / 5.0) * 5.0 / 100.0;

**

Wilz5363
  • 79
  • 8
  • You have 2 separate problems here... probably should have been two questions? (1) You want to round to 1 decimal place, **except** when the second decimal place is a 5. That's not a normal way to round, so no, your code isn't going to do that—you're just calling the library function `Math.round()`, which of course is going to do something more normal. (2) You want to **print** your number with 2 decimal places, and it's not doing that for you. – Dan Getz Jun 04 '15 at 05:43
  • if I dont use Math.round(), do you have any suggestion? Sorry to say but this rounding system exist in my country.. so jz gotta follow right? – Wilz5363 Jun 05 '15 at 11:59
  • It's the sentence near the bottom that says that 38.87 goes to 38.90 that confused me about your rounding system. I understand now, with your edit showing that 38.87 goes to 38.85. You're rounding to the nearest 0.05. – Dan Getz Jun 05 '15 at 16:27

1 Answers1

1

I would recommend you to use BigDecimal instead of double when you are dealing with money.

And then it would be like

BigDecimal value = new BigDecimal(38.84);
value = value.setScale(2, BigDecimal.ROUND_HALF_UP)

You can refer Javadocs for ROUND_HALF_UP and setScale

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331