user1613360
user1613360

Reputation: 1314

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

Upvotes: 0

Views: 2973

Answers (2)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35587

You need to try in this way

BigDecimal result=new
           BigDecimal("1333.212123232432543534324243253563453423423242452543535")
                                     .multiply(new BigDecimal("10").pow(1200));
System.out.println(result);

For your Edit:

BigDecimal result=new 
          BigDecimal("1333.212123232432543534324243253563453423423242452543535")
                                       .multiply(new BigDecimal("10").pow(1200));
System.out.println(result.movePointRight(-1200));

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503749

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).

Upvotes: 5

Related Questions