Question

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?

Was it helpful?

Solution

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

OTHER TIPS

BigInteger d = new BigInteger("12345");
BigDecimal one = new BigDecimal(d, 3);//12.345
BigDecimal two = new BigDecimal(d, 2);//123.45

Try this out :

String data = "12345678";
    StringBuilder builder = new StringBuilder(data);
    int x = 4;
    builder.insert(builder.length() - x, ".");

    System.out.println(builder);

Divide the value by 10 raise to the power x.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top