How to add decimal point before x digits in Java

Jaffy picture Jaffy · Mar 25, 2013 · Viewed 8k times · Source

Lets suppose I have a value 12345678 and a number say x=2, and I want the final output as 123456.78 and if the value of x is 4, the final output would be 1234.5678.

Please tell how would I can achieve this?

Answer

Jon Skeet picture Jon Skeet · Mar 25, 2013

Given that you're dealing with shifting a decimal point, I'd probably use BigDecimal:

long integral = 12345678L;
int x = 4; // Or 2, or whatever
BigDecimal unscaled = new BigDecimal(integral);
BigDecimal scaled = unscaled.scaleByPowerOfTen(-x);
System.out.println(scaled); // 1234.5678