Java BigDecimal to String

In this post, we will see how to convert BigDecimal to String in java.

There are many ways to convert BigDecimal to String in java. Some of them are:

  • Using toString()
  • Using String.valueOf()

toString method

You can simply use BigDecimal’s toString method to convert BigDecimal to String.

When you run above program, you will get below output:

20.234

String’s ValueOf method

You can also use String’s ValueOf() method to convert BigDecimal to String but it internally uses BigDecimal’s toString method only, so it is better to use BigDecimal’s toString method

When you run above program, you will get below output:

20.234

Issues with toString

You might not find expected result when you use BigDecimal constructor which takes double as argument.
For example:

When you run above program, you will get below output:

20.23400000000000176214598468504846096038818359375

Did you just expect 20.234 as output?
I think Yes. But issue is when you use BigDecimal constructor which takes double as argument, double cannot represent 20.234 exactly.
You need to either use String based constructor or use BigDecimal.valueOf method to solve this issue.
We have already seen String based constructor in above example.

When you run above program, you will get below output:

20.234

That’s all about BigDecimal to String conversion.


You may also like:

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *