This content has been marked as final. Show 9 replies
Rounding is necessary.
but i don,t want to make rounding
when input goes 10.0 it makes value to 10.00
but when input goes 10.66 it throws error but i want value as 10.66
The exception is thrown by BigDecimal.setScale(). See the Javadoc.
A simpler approach to perform the rounding would be to use format1 person found this helpful
However, if you really want to use BigDecimal you can do
String dividendAmountStr = String.format("%.2f", dividendAmount);
Edited by: Peter Lawrey on Jul 11, 2011 3:55 PM
String dividendAmountStr = BigDecimal.valueOf(dividendAmount).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
thanks for your reply
But i still confuse that
String DividendAmountStr=String.valueOf(new BigDecimal(DividendAmount).setScale(2));
above code worked fine with jdk 1.3 but now i am shifted to 1.6 then i got this error
is there any version issue?
That code worked with the same values in 1.3?
It is possible Java 1.3 was not so perdantic. ALso it is easy to write prgrams with bugs in them which just happen to work the way they are used. Doing things a little differently reveals the bug.
The problem comes from the use of new BigDecimal(double). This gives a faithful reproduction of the underlying double value. Many methods which convert double to another type allow for a small rounding error in the double, this constructor does not.
Even a simple value like 0.1 has a small rounding error for double type. Normally this is not obvious, with BigDecimal it is.
double d = 0.1; System.out.println("d= " + Double.toString(d)); BigDecimal bd = new BigDecimal(d); System.out.println("bd= " + bd); BigDecimal bd2 = BigDecimal.valueOf(d); System.out.println("bd2= " + bd2);
As you can see the second method for converting a double doesn't have this round issue for this value. This might be a temping option and it might work most of the time, however using setScale() with a rounding option will work every time.
d= 0.1 bd= 0.1000000000000000055511151231257827021181583404541015625 bd2= 0.1
It is possible Java 1.3 was not so pedantic.It is more probable that this value didn't arise in the 1.3 test.
Problem was not of version.
It was double value which was throwing error
BigDecimal bd2 = BigDecimal.valueOf(d).setScale(2);
above statement worked find