Numbers: Math, BigDecimal and random values
The Math class has the everyday helpers: Math.max, Math.min, Math.abs, Math.pow, Math.sqrt, Math.round, Math.floor and Math.ceil.
double stores binary fractions, so some decimals can't be exact: 0.1 + 0.2 == 0.3 is false. For money, use BigDecimal:
- Create it from a String,
new BigDecimal("19.99"), never from a double. - It's immutable:
a.add(b)returns a new value. - Set scale and rounding explicitly:
setScale(2, RoundingMode.HALF_UP). - Compare with
compareTo, because2.0and2.00aren'tequals.
For random numbers use ThreadLocalRandom.current().nextInt(1, 7) (a dice roll; 7 is excluded), or SecureRandom for passwords, OTPs and tokens.
Math.addExact and Math.multiplyExact throw an exception instead of silently overflowing.
Example
System.out.println(0.1 + 0.2); // 0.30000000000000004
BigDecimal price = new BigDecimal("499.99");
BigDecimal gst = price.multiply(new BigDecimal("0.18"))
.setScale(2, RoundingMode.HALF_UP); // 90.00
BigDecimal total = price.add(gst); // 589.99
System.out.println(new BigDecimal("2.0").equals(new BigDecimal("2.00"))); // false
System.out.println(new BigDecimal("2.0").compareTo(new BigDecimal("2.00"))); // 0: same value
int dice = ThreadLocalRandom.current().nextInt(1, 7); // 1 to 6
long ok = Math.multiplyExact(1_000_000L, 5_000L); // 5,000,000,000
double side = Math.sqrt(Math.pow(3, 2) + Math.pow(4, 2)); // 5.0
int boom = Math.addExact(Integer.MAX_VALUE, 1); // throws ArithmeticExceptionCommon mistake
Creating a BigDecimal from a double: new BigDecimal(0.1) is 0.1000000000000000055511151231257827… Use new BigDecimal("0.1") or BigDecimal.valueOf(0.1).
Under the hood
Store money as NUMERIC(12,2) in PostgreSQL, or as whole paise in a long; payment gateways such as Razorpay take amounts in paise for exactly this reason. Math.random() and new Random() are fine for games but predictable, so never use them for OTPs or reset links. Math.round(-2.5) is -2 because it rounds half up towards positive infinity.
Check yourself
Which correctly checks that two BigDecimal amounts have the same value?
How this connects
Know these first
Where this leads
You've reached the end of this thread. Try a learning path for what's next.
Part of Java from zero.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.