I'm fairly new to the whole android scene, and I decided to start off with something simple, a Celsius to Fahrenheit converter. Here's the block of code I'm using to do the actual math (x-32)*5/9 where x=input for Celsius Temp.
convertbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
double result = new Double(input.getText().toString())-32*5/9;
output.setText(Double.toString(result));
I know that x-32*5/9 is not a valid way to do the (x-32)*5/9 formula, but I can't put the -32 in parenthesis. Just looking for ways to get it to subtract 32 from the input first, and then for it to multiply that by 5/9. Any help would be much obliged.
You may have been confused by the parentheses in this expression:
new Double(input.getText().toString())-32*5/9
It would work if you parenthesized the whole thing up to 32:
(new Double(input.getText().toString())-32)*5/9
^ here and here ^
But it’s easier to read if you put the value in a temporary variable:
double input_value = new Double(input.getText().toString());
double result = (input_value - 32) * 5/9;
You are probably looking for Double.parseDouble(String);
Here is an example...
String s = "56.7";
double input = Double.parseDouble(s);
input = (input - 32d) * (5d/9d);
Edit: the d is necessary to force java to interpret the constants as doubles
Related
I'm trying to take user input in the form of myMonthlyPayment, myAnnualInterestRate, and myPrincipal in order to calculate the number of months needed to pay off debt by using The formula I've attached to this post. What I have in eclipse for the formula right now is:
monthsNeeded = ((Math.log(myMonthlyPayment) - Math.log(myMonthlyPayment)
- ((myAnnualInterestRate / 1200.0) * myPrincipal))
/ ((Math.log(myAnnualInterestRate) / 1200.0) + 1.0));
I should be getting an output of 79 months with the inputs I'm using but instead I'm getting -62. I know the formula is correct, I'm almost positive I've made a mistake somewhere in the translation of it into Java. If someone could point it out that would be greatly appreciated!
So I've fixed it, with a sample input and output.
I didn't put much effort into making this code beautiful but you can see that even separating it into 3 parts using method extraction (although I didn't know how to name them, lacking the domain knowledge) made the code easier to understand.
public class Example {
public static void main(String[] args) {
double myMonthlyPayment = 2000;
double myAnnualInterestRate = 5;
double myPrincipal = 200000;
System.out.println(a(myMonthlyPayment));
System.out.println(b(myPrincipal, myAnnualInterestRate, myMonthlyPayment));
System.out.println(c(myAnnualInterestRate));
double monthsNeeded = (a(myMonthlyPayment) - b(myPrincipal, myAnnualInterestRate, myMonthlyPayment))
/ c(myAnnualInterestRate);
System.out.println(monthsNeeded);
}
private static double c(double myAnnualInterestRate) {
return Math.log((myAnnualInterestRate / 1200.0) + 1);
}
private static double b(double myPrinicipal, double myAnnualInterestRate, double myMonthlyPayment) {
return Math.log(myMonthlyPayment - (myAnnualInterestRate / 1200.0) * myPrinicipal);
}
private static double a(double myMonthlyPayment) {
return Math.log(myMonthlyPayment);
}
}
I think this is what you're looking for:
monthsNeeded = (Math.log(myMonthlyPayment) - Math.log(myMonthlyPayment - myAnnualInterestRate / 1200d * myPrincipal)) / Math.log(myAnnualInterestRate / 1200d + 1);
It seems that, in your solution, you weren't calculating your myAnnualInterestRate/1200*myPrincipal inside your second Math.log(...). You had also left some calculations outside of Math.log(...) in the bottom half of your equation.
If you have an equation that does an operation inside a natural log, when you convert that equation to Java code, the operation needs to still be done, inside the natural log:
ln(someNumber + 10)
would be converted to:
Math.log(someNumber + 10),
NOT:
Math.log(someNumber) + 10
Hope this helps and good luck. :)
I am new to Java, and I am reading a book on it now. The book does not give me the answer. I am using the following code:
package loanpayments;
public class LoanPayments {
public static void main(String[] args) {
double years = Double.parseDouble(args[0]);
double P = Double.parseDouble(args[1]);
double r = Double.parseDouble(args[2]);
double R = r / 100;
double A = P*(Math.E*Math.exp(R*years));
System.out.println(A);
}
}
I am testing the code with the following values:
years = 3
P = 2340
r = 3.1
First I have to divide r by 100 to get a correct value (in this case it becomes 0.031). The new value of 0.031 becomes capitalized R. Then I use the formula to find A.
I am getting an incorrect output of ~6980.712, when the output should instead be ~2568.060.
I am thinking that I put in the formula wrong, it should be this:
Pe^R(years)
In this case e is Euler's number (~2.71828)
If anyone could advise me on how to fix the formula, or some other mistake, I would much appreciate it, thanks.
Not needed to multiply with another e because Math.exp() is already the exponential function.
Here is my simple code
#Override
public void onClick(View v) {
try {
double price = Double.parseDouble(ePrice.getText().toString());
double percent = Double.parseDouble(ePercent.getText().toString());
double priceValue = price * percent/100.0f;
double percentValue = price - priceValue;
moneyToGet.setText(String.valueOf(priceValue));
moneyToPay.setText(String.valueOf(percentValue));
moneyToGet.setText("" + priceValue);
moneyToPay.setText("" + percentValue);
// catch
} catch (NumberFormatException ex) {
// write a message to users
moneyToGet.setText("");
}
}
});
This is a simple code for Percentage Calculator.
What I want is to avoid the Scientific Notation in my Calculator cause I don't want to explain to user what is Scientific Notation.
For example if I want to calculate 100,000,000 and cut 50% of it, it Should give me 50,000,000 which is giving me 5.0E7 And in my case this doesn't make any sense to the user. And of course I know both results are correct.
Thanks in Advance.
Check answer here. You can write
moneyToGet.setText(String.format("%.0f", priceValue));
You can try this DecimalFormat
DecimalFormat decimalFormatter = new DecimalFormat("############");
number.setText(decimalFormatter.format(Double.parseDouble(result)));
I would suggest using BigDecimals instead of doubles. That way you will have a more precise control over your calculation precision. Also you can get a non-scientific String using BigDecimal.toPlainString().
DecimalFormat decimalFormatter = new DecimalFormat("##.############");
decimalFormatter.setMinimumFractionDigits(2);
decimalFormatter.setMaximumFractionDigits(15);
This option will help you ##.## suffix 0 before decimal, otherwise output will be .000
btc.setText(decimalFormatter.format(btcval));
use this for displaying content
Use NumberFormater like
NumberFormat myformatter = new DecimalFormat("########");
String result = myformatter.format(yourValue);
This is my code and it whines about calc 2 and the result.
BigDecimal costNum1 = new BigDecimal(number3.getText().toString());
BigDecimal costNum2 = new BigDecimal(number1.getText().toString());
BigDecimal costNum3 = new BigDecimal(number2.getText().toString());
BigDecimal calc1 = costNum1.multiply(costNum2);
BigDecimal calc2 = calc1.divide("100");
BigDecimal calc3 = calc2.multiply(costNum3);
result.setText(calc3).toString());
Safe to say I'm quite new in this, I'm almost there but I can't make up what is wrong. It's for my first Android App.
BigDecimal#divide accepts another BigDecimal, not a String.
Try
calc2.divide(new BigDecimal("100"));
Also, you have one too many parentheses in your last line.
Try
result.setText(calc3.toString());
You should always count the number of left parens, and see if it matches the number of right parens. If you use an IDE like eclipse, it should point these problems out to you automatically.
I have an assignment and I need to get an input from the user to refine an answer to an x(the input of the user) number of decimal places. I'm going to refine my answer until there aren't any changes in the x decimal place.Can you please help on how I could achieve this answer?
It's not very clear what you are trying to achieve, but I think you want to accept a number and then round it up as the user specifies it.
Java's BigDecimal http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html class has all the functions you may need for this purpose. Please don't use the primary data types (float, double) as they will result in rounding errors sooner or later.
While it is true what #Thihara answers, maybe you need a bit simpler approach. Unless you need the precision of BigDecimal, you can do this:
int x = 4;
double value = 3.141593;
long answer = (long) (value * Math.pow(10, x));
The point is: multiply the value by 10^x and then convert to long (or int). Of course, this only works for small x.
There are a bunch of issues floating around here, that you should be aware of.
The first is that if you use a floating point number to represent your answer, you cannot represent every possible real number so you almost definitely will get rounding errors. Check out http://floating-point-gui.de/ for great information about this.
Secondly, when you print a float or double value, Java does some magic with it so that it looks nice. See Float.toString(float) and Double.toString(double) for more information.
So in reality, if you enter
double answer = 3.14159265;
it is stored as
3.141592650000000208621031561051495373249053955078125
which you can see using
System.out.println(new BigDecimal(answer));
So assuming you get your answer as a double (or float), you should use BigDecimal's setScale method. Also, if you want to limit the decimal places that your user can choose to the number visible when you print the double as a string, pass String.valueOf(answer) to BigDecimal's constructor.
Here is a little program that demonstrates how to do this
public static void main(String[] args) {
double answer = 3.14159265;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String input = null;
do {
System.out.println("Answer: " + answer);
System.out.println("How many decimal places do you want? ");
try {
input = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (input != null) {
try {
int decimalPlaces = Integer.parseInt(input);
if (decimalPlaces < 0) {
System.out.println("Enter a positive value.");
} else {
BigDecimal scaled = new BigDecimal(
String.valueOf(answer));
if (decimalPlaces > scaled.scale()) {
System.out
.println("Answer does not have that many decimal places.");
} else {
scaled = scaled.setScale(decimalPlaces,
RoundingMode.HALF_EVEN);
System.out.println("Rounded answer: " + scaled);
}
}
} catch (Exception e) {
System.out.println("Not a valid number.");
}
}
} while (input != null);
}
Most of the code is error/input checking. The real work is done by setScale. Just keep in mind that there are many boundary conditions when working with floating point numbers, and you should be good!