Kindly help me in understanding the following code,
BigDecimal d = new BigDecimal(000100);
System.out.println(d); // output is 64!!!!
BigDecimal x = new BigDecimal(000100.0);
System.out.println(x); // output is 100
Shouldn't we use BigDecimal to process int or long value in any scenario? (I mean leave about performance and stuff, I know its not advisable to use BigDecimal to process only int or long). My data has mix of both long and decimal values, so am trying to know about BigDecimal.
The problem is not with BigDecimal
but with the literal numbers you're passing in. When an int
literal starts with 0
, Java interprets it as an octal number.
An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.
That is why 000100
produces 64
-- 1008 is 64 in decimal.
Decimal literals don't have leading zeros, so don't use any.
BigDecimal d = new BigDecimal(100);