14

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?

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
user68883
  • 828
  • 1
  • 10
  • 26
  • Related: http://stackoverflow.com/questions/4051887/how-to-format-a-java-string-with-leading-zero – Thomas Weller Jun 17 '15 at 14:02
  • possible duplicate of [How to nicely format floating numbers to String without unnecessary decimal 0?](http://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0) – Thomas Weller Jun 17 '15 at 14:04

5 Answers5

6

try this..

MathContext mc = new MathContext(6); // 6 precision
BigDecimal bigDecimal = new BigDecimal(2.12000, mc);
System.out.println(bigDecimal.toPlainString());//2.12000
Ende Neu
  • 15,581
  • 5
  • 57
  • 68
Hiren
  • 1,427
  • 1
  • 18
  • 35
  • 2
    This doesn't answer OP's question, when he's got a BigDecimal already in hand . . . – GingerHead Jun 17 '15 at 14:10
  • yes it was my mistake now look at my answer @GingerHead btw thanks!! – Hiren Jun 17 '15 at 14:16
  • This assumes that 6 is the required precision always. – Naveed S Feb 13 '18 at 15:28
  • It didnt work for me.. The below code printing "100.25" `MathContext mc = new MathContext(6); BigDecimal i = new BigDecimal(100.250, mc); System.out.println(i.toPlainString());` And also what if I have to convert the BigDecimal object which returned from an method to String ? Here you hardcoaded the value right? – sparker May 09 '18 at 10:00
  • Yes @PadmanabhanVijendran the precision is hardcoded. I did not get you about the conversion. Please elaborate it or post a new question with what you tried, what you achieved and where you are facing the issue. – Hiren May 10 '18 at 05:23
2

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

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0
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

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

Nishant Bhardwaz
  • 924
  • 8
  • 21
-2

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