The difference between "new BigDecimal()" and "BigDecimal.valueOf()"

Raphael De Lio
2 min readDec 7, 2023

--

Twitter | LinkedIn | YouTube | Instagram

John, a fresh graduate, recently joined Xebia as a junior software developer. He’s working with Emma, an experienced senior developer, who’s been mentoring him through pair programming. During a session, John uses the ‘new’ keyword to create a BigDecimal, which leads Emma to gently explain the differences between this method and ‘BigDecimal.valueOf’,

Emma: You know, understanding the difference between BigDecimal.valueOf(double) and new BigDecimal(double) in Java is super important for accuracy in calculations.

John: Oh really? Don’t they both just create a BigDecimal from a double value?

Emma: Well, yes, but they do it in different ways. Let’s start with BigDecimal.valueOf(double). Imagine you’re printing a double value using System.out.println(d). The valueOf method basically converts the double to its String representation first. So, the BigDecimal you get is what you see on your screen — intuitive and user-friendly.

John: That sounds straightforward. But what about new BigDecimal(double)?

Emma: Ah, that’s where it gets interesting. The new BigDecimal constructor doesn’t just convert the double value. It represents it as accurately as possible, which often leads to more digits than you’d expect.

John: More digits? How come?

Emma: It’s all about how doubles are stored in binary. For instance, if you do new BigDecimal(0.1), you won’t just get 0.1. You’ll end up with a really precise value like 0.1000000000000000055511151231257827021181583404541015625. It’s because 0.1 can’t be perfectly represented in binary.

John: Wow, that’s a lot more precise than I thought. But also a bit overkill for everyday use, right?

Emma: Exactly! That’s why BigDecimal.valueOf is often preferred. It’s more about what you see and expect. But if you need extreme precision, like in scientific calculations, then new BigDecimal is your go-to.

John: Got it. So, it’s all about choosing the right tool for the job. valueOf for general use and new BigDecimal for when every tiny detail counts.

Emma: Precisely! Understanding these subtleties can really make a difference in programming.

John: Thanks, Emma! That actually makes a lot of sense. Java’s got some interesting quirks, doesn’t it?

Emma: Oh, absolutely. And that’s what makes programming fun!

Contribute

Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio

Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw

Follow Me on Social Media

Stay connected and dive deeper into the world of Java with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.

Twitter | LinkedIn | YouTube | Instagram

--

--

No responses yet