Currently, I'm practicing my JavaFX skills. Mostly, I'm trying to solve problem by myself, but this time it's out of my mind.
I decided to create a unit converter. Everything was OK until I wanted to get my calculations inside Labels Mine code works good, but I'm not happy to see 10 or more decimals when I input numbers like 155.54 etc.
Here's the code:
value = input.getText().toString();
dValue = Double.parseDouble(value);
public void temperatureHandler() {
if (cBox.getValue() == "Celsius (C)") {
celsiusOutput.setText(Double.toString(dValue));
fahrenheitOutput.setText(Double.toString((dValue * 1.8) + 32));
kelvinOutput.setText(Double.toString(dValue + 273.15));
}
else if (cBox.getValue() == "Fahrenheit (F)") {
celsiusOutput.setText(Double.toString((dValue - 32) / 1.8));
fahrenheitOutput.setText(Double.toString(dValue));
kelvinOutput.setText(Double.toString((dValue + 459.67) * 5/9));
}
else if (cBox.getValue() == "Kelvin (K)") {
celsiusOutput.setText(Double.toString(dValue - 273.15));
fahrenheitOutput.setText(Double.toString((dValue * 1.8) - 459.67));
kelvinOutput.setText(Double.toString(dValue));
}
}
I have some experience in using String formats, StringBuilders etc. But I have no idea how can I set precision inside Label. I want to set it to 2 decimals.
Thanks you in advance.
Use a decimal format to format / truncate your double to 2 decimal places..
Example
DecimalFormat df = new DecimalFormat("#.00");
df.format(myDouble);
in your case
DecimalFormat df = new DecimalFormat("#.00");
celsiusOutput.setText(df.format((dValue - 32) / 1.8));
Related
So, I have this following code to make a simple temperature app converter in Android Studio 4.0.1:
bt_converter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double tempC = Double.parseDouble(et_tempC.getText().toString());
DecimalFormat arredondar = new DecimalFormat("#.##");
double tempF = Double.parseDouble(arredondar.format(tempC * 1.8 + 32));
tv_tempF.setText(String.valueOf(tempF));
}
The problem is that when I run the app it crashes due to this statement:
DecimalFormat arredondar = new DecimalFormat("#.##");
And the same for:
DecimalFormat arredondar = new DecimalFormat("0.00");
In fact it crashes with every pattern started by "0" and involving point "."
I've tried to switch it to:
DecimalFormat arredondar = new DecimalFormat("#,##");
And it actually works but it is not showing two decimal places as intended, and no matter what tempC value I put in, the output is always some number point zero (xx.0).
For example:
for tempC = 10.11111111
it shows tempF = 50.0
When it should give me 50.19 or 50.2 instead.
I've reinstalled the app and cleaned the project, and even changed my windows 10 region settings (with regards to decimal symbols), but it still remains the same.
But please let me know if you need more details.
So, I came to a solution, and it works as intended.
I just changed the three last lines of code:
Before
DecimalFormat arredondar = new DecimalFormat("#.##");
double tempF = Double.parseDouble(arredondar.format(tempC * 1.8 + 32));
tv_tempF.setText(String.valueOf(tempF));
After:
DecimalFormat arredondar = new DecimalFormat("0.00");
double tempF = tempC * 1.8 + 32;
tv_tempF.setText(arredondar.format(tempF));
Apparently there is some king of error/incompatibility. But, I realised that I was converting tempF from String to Double with the second line in the before code, and then convert it back again to String with the third one.
So I simply put the tempF directly in the output with a String format, after having calculated it with no convertion:
double tempF = tempC * 1.8 + 32;
tv_tempF.setText(arredondar.format(tempF));
And I've changed the pattern from "#.##" to "0.00" to make sure that I get two decimal places everytime.
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 making a pizza calculator but my results come out as "$7.5" instead of "$7.50". I have this decimal format code written out with my code below it, but it doesn't seem to work. Any ideas?
private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
double diameter;
double labourCost = 1.00;
diameter = Double.parseDouble(diameterInput.getText());
double storeCost = 1.50;
double materialsCost = 0.50 * diameter;
double totalCost = labourCost + storeCost + materialsCost;
DecimalFormat x = newDecimalFormat("0.00");
costOutput.setText("The cost of the pizza is $" + totalCost);
You're not using the result ("x") of the operation for anything. I'm guessing that replacing "totalCost" with "x" in the last line will help?
You need to use a Decimal Formatter to convert your floating point value over to a string.
// Make a new formatter with your format
DecimalFormat myFormatter = new DecimalFormat("$##.00");
// Convert your number to a human readable string
String output = myFormatter.format(22.99999f);
System.out.println(output); // Prints $23.00
See this page for details on the various patterns https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
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);
I am trying to display numbers in a string dynamically, so if the number has decimal's display them but if not don"t show the .0
example: display 5.5 as 5.5 and 5.0 as 5
This is what I have so far: (answer is a double)
double temp = answer;
long temp2 = (long) temp;
if (temp == temp2) {
output = String.valueOf(temp2);
System.out.println(output);
this work's fine up to about 1e18 then will error out because of the maximum size of a Long.
So how would I achieve this on bigger numbers like 5.43e86
Use DecimalFormat
double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));
The DecimalFormat suggestions are the easiest way to handle this. If they aren't sufficient, here's another idea.
If you're starting to hit the maximum values that can be represented by primitives in Java, then you may need to move to BigInteger and BigDecimal.
Try playing around with the BigDecimal.toBigInteger() method coupled with the toString() methods on BigDecimal and BigInteger.
It's not good solution
if you use new DecimalFormat("0.#") you are missing data, for example
PI = 3.14, but after parse you ae geting 3.1
Another solution to use eval%1 ? (int)d : d
this time couse max integer limit , again missing data
my solution is working, but it's not good idea
res = removeLastChars(eval,".0");
private String removeLastChars(double eval, String text){
String res = String.valueOf(eval);
int length = text.length();
if (res.length() > length){
res = res.substring((res.length() - length), res.length()).equals(text)
? res.substring(0, (res.length() - length)) : res;
}
return res;
}
Look at
http://download.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
you would want just DecimalFormat("0.0")