Search code examples
javaroundingcurrencycurrency-formatting

How can I round money to the nearest cent?


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

Solution

  • 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;