14

I have a BigDecimal variable

BigDecimal x = new BigDecimal("5521.0000000001");

Formula:

x = x.add(new BigDecimal("-1")
      .multiply(x.divideToIntegralValue(new BigDecimal("1.0"))));

I want to remove the integer part, to get the value x = ("0.0000000001"), but my new value is 1E-10 and not the 0.0000000001.

Mat
  • 202,337
  • 40
  • 393
  • 406
user1609993
  • 141
  • 1
  • 1
  • 4

4 Answers4

23

To get a String representation of the BigDecimal without the exponent part, you can use
BigDecimal.toPlainString(). In your example:

BigDecimal x = new BigDecimal("5521.0000000001");
x = x.add(new BigDecimal("-1").
              multiply(x.divideToIntegralValue(new BigDecimal("1.0"))));
System.out.println(x.toPlainString());

prints

0.0000000001
Keppil
  • 45,603
  • 8
  • 97
  • 119
3

Try using BigDecimal.toPlainString() to get value as plain string as you require.

Akhilesh Awasthi
  • 2,688
  • 4
  • 21
  • 30
2

Perhaps using BigDecimal isn't really helping you.

double d = 5521.0000000001;
double f = d - (long) d;
System.out.printf("%.10f%n", f);

prints

0.0000000001

but the value 5521.0000000001 is only an approximate representation.

The actual representation is

double d = 5521.0000000001;
System.out.println(new BigDecimal(d));
BigDecimal db = new BigDecimal(d).subtract(new BigDecimal((long) d));
System.out.println(db);

prints

5521.000000000100044417195022106170654296875
1.00044417195022106170654296875E-10

I suspect whatever you are trying to is not meaningful as you appear to be trying to obtain a value which is not what you think it is.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

If you want to do this at your BigDecimal object and not convert it into a String with a formatter you can do it on Java 8 with 2 steps:

  1. stripTrailingZeros()
  2. if scale < 0 setScale to 0 if don't like esponential/scientific notation

You can try this snippet to better understand the behaviour

BigDecimal bigDecimal = BigDecimal.valueOf(Double.parseDouble("50"));
bigDecimal = bigDecimal.setScale(2);
bigDecimal = bigDecimal.stripTrailingZeros();
if (bigDecimal.scale()<0)
bigDecimal= bigDecimal.setScale(0);
System.out.println(bigDecimal);//50
bigDecimal = BigDecimal.valueOf(Double.parseDouble("50.20"));
bigDecimal = bigDecimal.setScale(2);
bigDecimal = bigDecimal.stripTrailingZeros();
if (bigDecimal.scale()<0)
bigDecimal= bigDecimal.setScale(0);
System.out.println(bigDecimal);//50.2
bigDecimal = BigDecimal.valueOf(Double.parseDouble("50"));
bigDecimal = bigDecimal.setScale(2);
bigDecimal = bigDecimal.stripTrailingZeros();
System.out.println(bigDecimal);//5E+1
bigDecimal = BigDecimal.valueOf(Double.parseDouble("50.20"));
bigDecimal = bigDecimal.setScale(2);
bigDecimal = bigDecimal.stripTrailingZeros();
System.out.println(bigDecimal);//50.2