Skip to main content

Small bug with java.math.BigDecimal

2 replies [Last post]
auguur
Offline
Joined: 2010-10-18

Hello,

I noticed that the BigDecimal class incorrectly adds a number to itself when the initial value is Zero.

Example

var1 = new BigDecimal(0);
var2 = new BigDecimal(17);
var3 = var1.add(var2); // var3 should be 17, but result is 0;

Hope this helps.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
ddmarx
Offline
Joined: 2007-08-17

import java.math.BigDecimal;

import static java.lang.System.out;

/**
* http://forums.java.net/jive/thread.jspa?messageID=485527
*/
public class BigDecimalTest
{
/**
* http://forums.java.net/jive/thread.jspa?messageID=485527
*/
public void testBigDecimalAdd()
{
final BigDecimal var1 = new BigDecimal(0);
final BigDecimal var2 = new BigDecimal(17);
final BigDecimal var3 = var1.add(var2);
out.println(var1 + " + " + var2 + " = " + var3);
}

public static void main(final String[] arguments)
{
final BigDecimalTest instance = new BigDecimalTest();
instance.testBigDecimalAdd();
}
}

Prints out: 0 + 17 = 17

sujikin
Offline
Joined: 2005-04-03

public void testSum(){
BigDecimal var1 = new BigDecimal(0);
BigDecimal var2 = new BigDecimal(17);
BigDecimal var3 = var1.add(var2); // var3 should be 17, but result is 0;
System.out.println(var3.longValue());
}

This prints 17. Can you please reproduce the whole code?