Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does int + BigDecimal not work?

Tags:

java

I encountered this problem, which was that I couldn't add an integer to a BigDecimal. In the code, I looked at the error and it said "bad operand types for binary operator '+'". How do I add integer to BigDecimal? (Represented in code as 1 + sqf)

BigDecimal sqf = new BigDecimal(Math.sqrt(5));
sqf.setScale(100);
BigDecimal bd = new BigDecimal((1 + sqf) / 2); //Error here (1 + sqf)
bd.setScale(100);
System.out.println(isBuzzNumber(77707));
System.out.println(findHypotenuse(9, 10));
System.out.println("Phi (φ) = " + bd);
like image 391
TessellatingPi Avatar asked Oct 17 '25 02:10

TessellatingPi


2 Answers

BigDecimal bd = BigDecimal.ONE.add(sqf).divide(new BigDecimal(2))

Standard operators apply to primitives only.

like image 71
dpington Avatar answered Oct 18 '25 15:10

dpington


  1. Java doesn't have operator overloading, thus any standard operator applies to primitive type only
  2. BigDecimal isn't included in the autoboxing mechanism, because it doesn't have primitive type representation
  3. Read up BigDecimal API, it implements mathematical operators as methods (which mostly requires another BigDecimal instance as operand.
like image 35
LeleDumbo Avatar answered Oct 18 '25 15:10

LeleDumbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!