可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
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
回答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.
回答3:
Try using BigDecimal.toPlainString() to get value as plain string as you require.
回答4:
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:
- stripTrailingZeros()
- 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