How to retain trailing zeroes when converting BigDecimal to String

15k views Asked by At

I have to convert a BigDecimal value, e.g. 2.1200, coming from the database to a string. When I use the toString() or toPlainString() of BigDecimal, it just prints the value 2.12 but not the trailing zeroes.

How do I convert the BigDecimal to string without losing the trailing zeroes?

5

There are 5 answers

5
Hiren On

try this..

MathContext mc = new MathContext(6); // 6 precision
BigDecimal bigDecimal = new BigDecimal(2.12000, mc);
System.out.println(bigDecimal.toPlainString());//2.12000
3
Davide Lorenzo MARINO On

To convert a BigDecimal to a String with a particular pattern you need to use a DecimalFormat.

BigDecimal value = .... ;
String pattern = "#0.0000"; // If you like 4 zeros
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);

To check the possible values of pattern see here DecimalFormat

0
Gaurav vijayvargiya On
double value = 1.25;
// To convet double to bigdecimal    
BigDecimal bigDecimalValue = BigDecimal.valueOf(value);   
//set 4 trailing value
BigDecimal tempValue = bigDecimalValue.setScale(4, RoundingMode.CEILING);
System.out.println(tempValue.toPlainString());
0
Nishant Bhardwaz On

You can use below code .

    BigDecimal d = new BigDecimal("1.200");
    System.out.println(d);
    System.out.println(String.valueOf(d));

Output is as below :
1.200 1.200

0
TheArrowster On

In a practical way, just don't use BigDecimal, instead use toString() of Double class.