4

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?

Jaffy
  • 575
  • 1
  • 6
  • 15
  • 3
    divide it by `100.0` for X 2, and by `1000.0` for X 4 – Habib Mar 25 '13 at 06:57
  • possible duplicate of http://stackoverflow.com/questions/1050989/double-greater-than-sign-in-java – Drogba Mar 25 '13 at 06:57
  • @Habib: I don't think that brining floating-point into it is necessarily a great idea (assuming the `12345678` in the question is an `int`.) – NPE Mar 25 '13 at 06:58
  • 1
    @NPE: I think it's fine to bring floating-point into it. I just wouldn't bring floating *binary* point. – Jon Skeet Mar 25 '13 at 07:02
  • @JonSkeet: I don't know about you, but I've not actually seen a single hardware implementation of floating *decimal* point. :) It's a bit like saying that we can't compute an integer power of two by using the shift operator because this assumes a binary computer and not, say, a ternary one (http://en.wikipedia.org/wiki/Setun) :) – NPE Mar 25 '13 at 07:04
  • @NPE: Who said anything about a hardware implementation? `BigDecimal` is the Java representation of a floating decimal point number, just like `System.Decimal` is the .NET representation. – Jon Skeet Mar 25 '13 at 07:10

4 Answers4

12

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
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6
BigInteger d = new BigInteger("12345");
BigDecimal one = new BigDecimal(d, 3);//12.345
BigDecimal two = new BigDecimal(d, 2);//123.45
rajesh
  • 3,247
  • 5
  • 31
  • 56
2

Try this out :

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

    System.out.println(builder);
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
1

Divide the value by 10 raise to the power x.

Prateek Shukla
  • 593
  • 2
  • 7
  • 27