0

So I am creating a tip calculator app but I am struggling to round to the nearest cent; here are some random edge cases I came up with

$1.243 => $1.25 
$4.44134242 => $4.45
$5.5675235235 => $5.57
$1.21 => $1.21
$1.2000 => $1.20
$1.20001 => $1.21

In essence, I am looking at the hundredth's place and if there is any number greater than 0 after that decimal place, I round it up to the nearest cent. Below is what I came up with but I am sometimes off by a cent

double value = 123.451;
double amount = (int)(value * 100.0) / 100.0;
// Should return 123.46
  • 4
    I don't understand why 1.243 rounds to 1.24 rather than 1.25, given your description of what you want. – tgdavies Feb 08 '21 at 04:01
  • It's better to use `java.math.BigDecimal` for money calculations. More details here https://stackoverflow.com/a/9959347/2224047 – Nikolai Shevchenko Feb 08 '21 at 04:03
  • 1
    In the title you say "nearest 2 cents" but the rest of the question just talks about roundig up to the next cent. What is the actual requirement? – Henry Feb 08 '21 at 04:16
  • Yes that was a typo $1.243 should round to $1.25 (updated), I meant 2 decimal places. In essence, if you and someone else were splitting a bill, and hypothetically if you were to split it evenly, you and your friend would give $1.25 instead of some large "weird" decimal value. – Eliteness CA Feb 08 '21 at 18:45

1 Answers1

1

Assuming you understand the characteristics of floating point numbers and the drawback it has for monetary calculations, something like this?

double amount = Math.ceil(value * 100.0) / 100.0;
Henry
  • 42,982
  • 7
  • 68
  • 84