Search code examples
javabigdecimal

BigDecimal to String in java?


My code is:

x=new BigDecimal(x.toString()+" "+(new BigDecimal(10).pow(1200)).toString());

I am trying to concat two bigdecimals after converting them to string and then convert them back to bigdecimal.I am doing so because x has a value with a decimal point and multiplying will change its value.It compiles fine but throws a numberformat exception on execution.

My idea was to use the BigDecimal("String x") constructor to convert the string back to BigDecimal.

Note: (for example) x=1333.212 and I am converting it to x=1333.2120000


Solution

  • It's failing to parse because you've got a space in there for no particular reason. Look at the string it's trying to parse, and you'll see it's not a valid number.

    If you're just trying to add extra trailing zeroes (your question is very unclear), you should change the scale instead:

    x = x.setScale(x.scale() + 1200);
    

    Simple example:

    BigDecimal x = new BigDecimal("123.45");
    x = x.setScale(x.scale() + 5);
    System.out.println(x); // 123.4500000
    

    If you were trying to multiply the value by a power of 10 (as your initial question suggested), there's a much simpler way of doing this, using movePointRight:

    x = x.movePointRight(1200);
    

    From the docs:

    The BigDecimal returned by this call has value (this × 10n) and scale max(this.scale()-n, 0).