BigDecimal assign operator - java

I have a problem with assigning one big decimal value to another
I am trying such as creating one temp big decimal and add 0 to another big decimal
BigDecimal temp = new BigDecimal(0);
dropStartValue = temp.add(newCounterValue);
However, I only want simply do the operation below on big decimals:
dropStartValue = newCounterValue

You haven't specified the type of either dropStartValue or newCounterValue. If they're both BigDecimals, then this should be fine:
dropStartValue = newCounterValue;
Note that although that's just making both variables refer to the same object, it's safe because BigDecimal itself is immutable.
If that's not working for you, please give details of what problems you're seeing (exceptions? compile-time errors?).

Assuming this is Java ans newCounterValue is an integer type or a box thereof, dropStartValue = new BigDecimal(newCounterValue); should do what you want.

Related

BigDecimal math operations

I want to write this in Java but I get some errors and I am not sure how to write it:
C = A - (A*B)/100
All of my values are defined as Bigdecimal objects.
I tried something like this but is not working:
C = A.subtract(A.multiply(B).divide(100));
..I get a warning to add more arguments to the divide method. I do not know how to write it correctly. What am I doing wrong? Thanks in advance
BigDecimal has no divide(int) method, but that's what you're asking it to do with .divide(100), because 100 is an int literal. If you refer to the documentation, all of the divide methods accept BigDecimal instances.
You can use divide(BigDecimal) instead, by using BigDecimal.valueOf:
C = A.subtract(A.multiply(B).divide(BigDecimal.valueOf(100)));
(It accepts a long [or double], but int can be promoted to long.)
Alternately, for some values, you might use the String constructor instead:
C = A.subtract(A.multiply(B).divide(new BigDecimal("100")));
...particularly if you're dealing with floating-point values that might lose precision in double. 100 is fine for valueOf, though.
c = a.subtract(a.multiply(b).divide(BigDecimal.valueOf(100.0)));

Wrapper Classes, Difference in functionality when creating object via a String parameter in Constructor?

In terms of instances of wrapper classes, does the instance behave differently when the instance is created via a String arg in the constructor in comparison to an int, double etc.
E.g is there a difference in:
Integer wrapperInt= new Integer(33);
Integer wrapperInt2= new Integer("33");
The end result will be the same - you'll have an Integer object with the value 33.
The version that takes a String will throw a NumberFormatException if the input string cannot be parsed.
Note: There's no need to write a statement like Integer wrapperInt = new Integer(33);. Let the compiler do it for you (auto-boxing):
Integer wrapperInt = 33;
If, for some reason, you do not want to use auto-boxing, then at least use Integer.valueOf(...) instead of using the constructor:
Integer wrapperInt = Integer.valueOf(33);
This is more efficient; the valueOf method can return a cached object (so that it's not necessary to create a new Integer object).
No, it doesn't. Both instances represent the integer 33. If there was a difference, it would be written in the javadoc.
Note that you should favor the usage of the factory methods instead:
Integer i = Integer.valueOf(33);
i = Integer.valueOf("33");
The only difference is you will be creating a string object unnecessarily in the second approach and it will try to parse the string you have passed to the constructor, If it couldn't parse the string then it will throw NumberFormatException.
The answer is that yes, there can be a difference between the two syntaxes. Specifically, the syntax
new Integer(33);
results in the value 33 being interpreted as an integer constant by the compiler and stored as a literal in the code. By contrast, the syntax
new Integer("33");
results in a call that routes the string value through Integer.parseInt(s, 10). This matters if the value in question has a leading zero character; in the case of an int literal, the compiler will evaluate the literal as octal:
new Integer(010); // equals 8
By contrast, the string constructor will always evaluate the value as base 10:
new Integer("010"); // equals 10
In any case, you should almost always be using Integer.valueOf(), as it is usually more efficient.

BigDecimal rounding not rounding

I'm very new to android programming so any help would really be appreciated.I have gone through the pages and do not seem to find the right answer. If this is a similar question I honestly do apologize.
My problem is that when I wrote the code on my android device with AIDE compiler the rounding of example below
pitch_round.setScale(2,BigDecimal.ROUND_UP);
worked fine and I was able to output the rounded bigdecimal to a TextView by using pitch_round.ToString() , when I used similar code in Eclipse there wasn't an error in compiling but the ouput to textview did not seem to round at all , if i am not mistaken there seems to be more decimal characters now.
Below is a snippet of the code that is not working.Is there something that I am not doing right here? All falues are floats
This is identical to the code that was used on AIDE on the device
Thank you in advance
pitch = mOrientation[1]*57.2957795f;
roll= mOrientation[2]*57.2957795f;
yaw= mOrientation[0]*57.2957795f;
// change to bigdecimal object
BigDecimal pitch_round = new BigDecimal(pitch-zero_pitch);
BigDecimal roll_round = new BigDecimal(roll-zero_roll);
BigDecimal yaw_round = new BigDecimal(yaw-zero_yaw);
pitch_round.setScale(2,BigDecimal.ROUND_UP);
roll_round.setScale(2,BigDecimal.ROUND_UP);
yaw_round.setScale(2,BigDecimal.ROUND_UP);
Log.i(SENSOR_SERVICE, pitch_round.toString());
t_pitch.setTextColor(Color.CYAN);
t_roll.setTextColor(Color.CYAN);
t_yaw.setTextColor(Color.CYAN);
// log some output to test code
//Log.i(SENSOR_SERVICE, "Send Results"+ pitch);
t_pitch.setText(pitch_round.toString());
t_roll.setText(roll_round.toString());
t_yaw.setText(yaw_round.toString());
Change all like
pitch_round.setScale(2,BigDecimal.ROUND_UP);
to
pitch_round = pitch_round.setScale(2,BigDecimal.ROUND_UP);
BigDecimal is immutable, calls of this method do not result in the original object being modified
setScale returns a new BigDecimal, which you're discarding. Try
pitch_round = pitch_round.setScale(2,BigDecimal.ROUND_UP);
From the setScale API doc:
Note that since BigDecimal objects are immutable, calls of this method
do not result in the original object being modified, contrary to the
usual convention of having methods named setX mutate field X. Instead,
setScale returns an object with the proper scale; the returned object
may or may not be newly allocated.

Difference between BigDecimal.ONE and new BigDecimal("1")

what is the difference between below two lines of code?
BigDecimal one = new BigDecimal("1");
BigDecimal two = BigDecimal.ONE;
Are both the lines same?
Thanks!
No, they're not quite the same - new BigDecimal("1") allocates a new object each time it's executed (and have to parse the value, too); BigDecimal.ONE will use a reference to the same existing object each time.
As BigDecimal is immutable, you can reuse an existing instance freely - so it makes sense to refer to a "pre-canned" object where you know what the value will be.
BigDecimal.ONE is a pre scanned object and its efficient in terms of memory utilization as compared to
BigDecimal one = new BigDecimal("1");
because in this line it first creates an instance and then parses string "1" and then assigns.
whereas BigDecimal.ONE is like a constant and will give you direct value.
Hope this helps!

Converting from String to BigDecimal to do math on currency

I am working on a project that requires some simple math to be performed on currency, however it arrives in the form of a String. I am new to Java/Android so I am looking for help in converting from a String to a data type appropriate to this operation. At first I thought Float was right but after reading elsewhere and introducing myself to the numbers class, it appears BigDecimal is correct. Am I on the right track? At this point I simply want to subtract the sum of payments from an initial invoice amount. I get the feeling this code is simple but clumsy and I suspect I am missing a great deal about the nuances of working with currency. How would you do it? All advice warmly appreciated!
// capture variables from sending activity
String invoiceAmt = getIntent().getStringExtra("invoiceAmt");
String paymentsSum = getIntent().getStringExtra("paymentsSum");
// convert strings to BigD's
BigDecimal amt = new BigDecimal(invoiceAmt);
BigDecimal sum = new BigDecimal(paymentsSum);
// Do the math
BigDecimal invDue = amt.subtract(sum);
// insert the value (back to string) into textView
TextView tvInvoiceDue = (TextView)findViewById(R.id.InvoiceDue);
tvInvoiceDue.setText(invDue.toString());
BigDecimal is a fine approach. So is using an int or a long to store cents. I've heard some people like Joda-Money but I've never used it myself.
See this question.
In the code you posted, make sure the Strings you are receiving don't have currency symbols in them.

Categories