From the course: Java 8+ Essential Training: Syntax and Structure

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Store currency values with BigDecimal

Store currency values with BigDecimal - Java Tutorial

From the course: Java 8+ Essential Training: Syntax and Structure

Start my 1-month free trial

Store currency values with BigDecimal

- Primitive numeric variables are useful for storing single values in memory, but variables using the double and float types aren't always precise. That's because of the way they're stored in memory. It doesn't exactly map to the value that you declare in your programing. For example, a double value is supposed to take 64 bits but Java doesn't use all 64 bits. It only stores what it considers the important parts of the number. So you can see some pretty odd things when you start adding values together and then outputting the result. In jshell, I'll declare a double variable that I'll name "value" and I'll give it a literal value of .012. I see the response immediately, and that looks accurate. Now I'll create another double value that I'll call pSum for "primitive sum," and I'll get that value by adding the original variable three times. With value plus value plus value, and I immediately see something odd. Instead of simply .036 like I expect, I get a bunch more places in the number,…

Contents