1

In my code, if I convert a string, for example

String str = ".12";
String str2 = "0.12"

to Bigdecimal, both gives me the output 0.12. My output requires me not to change the notation - is there a way I can have BigDecimal conversion from string in this case not add 0 to it for .12? I am okay when it keeps 0.12 to 0.12.

I just want the Bigdecimal to preserve the string input exactly the way it is, no adding of zeroes, no removing of zeroes.

I am doing this:

Bigdecimal bd = new Bigdecimal(str);
bd.toString() gives me 0.12
java_doctor_101
  • 3,287
  • 4
  • 46
  • 78
  • [Related question](http://stackoverflow.com/questions/3395825/how-to-print-formatted-bigdecimal-values) – augray Jan 18 '16 at 02:52
  • I have come to the conclusion that this can't be done using any formatting or using a function of Bigdecimal class. Only way I could find is to print out the original string. Still waiting for an answer though. – java_doctor_101 Jan 18 '16 at 15:42
  • 1
    As you found out, BigDecimal can not be made *not* to output the single `0` in front of the decimal point. BigDecimal does not keep track of the original string, so it does not know if a leading `0` was present, it only parses it to its internal representation. So yes, your only solution is to keep track of the string yourself. – Rudy Velthuis Jan 18 '16 at 16:49

3 Answers3

1

As you can read here the dot devides the IntegerPart from the FractionPart. So in your case the 0 is added as the IntegerPart because u only pass a fractionPart

Daniel
  • 1,027
  • 1
  • 8
  • 23
  • Daniel, thanks for the reply. You said I only passed a fractionPart, can you point me to the function which takes both the parts? – java_doctor_101 Jan 18 '16 at 03:22
1

Hope this help :)

If it's okay with you can create a subclass for BigDecimal like say:

class CustomBigDecimal extends BigDecimal{

String originalValue;

public CustomBigDecimal(String str) {
    super(str);
    originalValue=str;
}

public String toString(){
    return originalValue;

}
}

then use it like this:

CustomBigDecimal cbd1 = new CustomBigDecimal("0.12");
System.out.println(cbd1);
CustomBigDecimal cbd2 = new CustomBigDecimal(".12");
System.out.println(cbd2);

Output:

0.12
.12
LChukka
  • 11
  • 4
-2

One way is to format the String returned from toString() and remove the leading zero manually:

bd.toString().replaceFirst("^0\\.", ".");

Bifz
  • 403
  • 2
  • 9