Java Reference
In-Depth Information
erwise, it sets the scale to zero, and multiplies the integer value by 10. If n
is negative, the call is equivalent to movePointLeft(-n).
BigDecimal comparisons and conversions
Several methods of the BigDecimal class provide comparison of
BigDecimal numbers with other objects, as well as conversion between
BigDecimal numbers and other formats. The comparison methods are
equals() and compareTo(), while the conversion methods are
doubleValue(), floatValue(), intValue(), longValue(), toBigInteger(),
valueOf(), toString(), and hashCode().
public boolean equals(Object x)
Compares a BigDecimal with the object specified as an operand. This
methodconsiderstwoBigDecimalnumbersequaliftheyareequalinvalue
andscaleonly.Thus,equalsreturnsthat3.0isnotequalto3.00.Themethod
returnsifbothBigDecimalobjectsareequalinvalueandscale,asinthefol-
lowing code fragment:
BigDecimal aNum = new BigDecimal ("3.45"); // String constructors
BigDecimal bNum = new BigDecimal ("3.450");
// Testing equals()
System.out.println(aNum.equals(bNum));
// FALSE
public int compareTo(BigDecimal val)
ComparestwoBigDecimalwiththespecifiedBigDecimalindependentlyof
scale. In contrast with the equals() methods, compareTo() does not con-
sider the scale of the operands when making comparisons. Also,
compareTo() returns an integer instead of a boolean.
The compareTo() method can be used with any of the six boolean com-
parison operators (<, ==, >, >=, !=, <=). The general form is:
(x.compareTo(y) <op> 0)
where x and y aretwoBigDecimalnumbersand<op>isoneoftheboolean
operators.Themethodreturns-1ifthefirstoperatorislessthanthesecond
one, 0 if both operators are equal, and 1 if the first one is greater than the
second one. For example:
BigDecimal aNum = new BigDecimal ("3.45"); // String constructor
BigDecimal bNum = new BigDecimal ("3.450");
BigDecimal cNum = new BigDecimal ("5.0");
int numVal = 0;
// Testing compareTo()
System.out.println(aNum.compareTo(bNum) == 0); // TRUE
numVal = aNum.compareTo(cNum);
// -1
System.out.println(numVal);
Search WWH ::




Custom Search