Java BigDecimal to String

Previous
Next

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 interanally 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 issues 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.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog