The problem is that you specify a custom format with your DecimalFormat
and then parse the resulting String
using the format specified by the default Locale
.
You have several options to solve the problem:
Use the same
DecimalFormat
object to both format and parse the number.Use a different rounding algorithm. For example:
double roundToHundredths(double d) { return (int)(d * 100) / 100.0; }
Store the number as an
int
in "hundredths". Do your calculations with thisint
and display it as a decimal.Use
BigDecimal
for greater precision.
Note that using a "rounded" number in any further calculations is still tricky since floating point numbers are imprecise. This means that the "rounded" result is not necessarily exact.