Table of Contents
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; import java.math.BigDecimal; public class BigDecimalToStringMain { public static void main(String[] args) { BigDecimal bigDecimal=new BigDecimal("20.234"); String toStringBigDec=bigDecimal.toString(); System.out.println(toStringBigDec); } } |
When you run above program, you will get below output:
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; import java.math.BigDecimal; public class BigDecimalToStringMain { public static void main(String[] args) { BigDecimal bigDecimal=new BigDecimal("20.234"); String valueOfBigDec=String.valueOf(bigDecimal); System.out.println(valueOfBigDec); } } |
When you run above program, you will get below output:
Issues with toString
You might not find expected result when you use BigDecimal constructor which takes double as argument.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; import java.math.BigDecimal; public class BigDecimalToStringMain { public static void main(String[] args) { BigDecimal bigDecimal=new BigDecimal(20.234); String toStringBigDec=bigDecimal.toString(); System.out.println(toStringBigDec); } } |
When you run above program, you will get below output:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; import java.math.BigDecimal; public class BigDecimalToStringMain { public static void main(String[] args) { String toStringBigDec=BigDecimal.valueOf(20.234).toString(); System.out.println(toStringBigDec); } } |
When you run above program, you will get below output:
That’s all about BigDecimal to String conversion.
You may also like: