0

Using BigDecimal what is the mode I should use for the below condition to round up to decimal point ?

If >= USD 0.005 rounds up to USD 0.01, If the amount is < USD 0.005 round down to 0.00.

Should I use RoundingMode.HALF_UP?

Alvin
  • 8,219
  • 25
  • 96
  • 177
  • 2
    aaaand what if `amount == 0.005`? (also, why `0.004` should become `0.01` but `0.006` should become `0.00`, shouldn't it be the opposite?) – Alberto Sinigaglia May 24 '21 at 12:48
  • 1
    Don't use big decimal for currency. Use an integer value of cents. – Michael May 24 '21 at 12:48
  • 1
    @Michael: That approach can work, but some currencies (Tunisian Dinar) have 1000 small things in the big thing. And Bitcoin has 8 decimal places. And some don't have a little thing at all (Japanese Yen). A BigDecimal could therefore be the right thing to use. – Bathsheba May 24 '21 at 12:52
  • @Bathsheba "USD". It doesn't matter how many small units are in a larger unit. Store Dinar as millims. Convert it later. – Michael May 24 '21 at 12:52
  • All the predefined rounding modes account for all possible values as input, and round to some definitely of "nearest". Your mode does neither as currently written, do you need to work that out before asking a question. – Mad Physicist May 24 '21 at 12:52
  • @Michael I took that to be an example. Sill, it won't be the last USD-only system ever built ;-) – Bathsheba May 24 '21 at 12:53
  • 1
    @Bathsheba. A big decimal is still not the right thing to use. Even if the small unit is 1e-6 of the big unit, you should use integers because there are no fractional small units – Mad Physicist May 24 '21 at 12:54
  • @Alvin. Please edit your question – Mad Physicist May 24 '21 at 12:54
  • 1
    @MadPhysicist: See https://stackoverflow.com/questions/8148684/what-data-type-to-use-for-money-in-java. Although I don't think I should disclose what I use in C++ as my money type ;-) – Bathsheba May 24 '21 at 12:55
  • @MadPhysicist I didn't use integer because I am calculating using percentage. – Alvin May 24 '21 at 12:56
  • @Alvin. What's that got to do with anything? Do you allow fractional cents? If not, use integers to store the values, or Currency – Mad Physicist May 24 '21 at 13:05

1 Answers1

2

I assume you want to round < 0.005 to 0.00 and > 0.005 to 0.01.

 BigDecimal bd = new BigDecimal(0.004999);
 bd =  bd.setScale(2, BigDecimal.ROUND_HALF_UP);
Tal Glik
  • 480
  • 2
  • 11