Decimal Format in Jframe? - java

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

Related

JavaFX Label double precision

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));

Displaying Currency Format Issue

First post. I'm brand new to software development in general and have spent hours trying to figure this piece out. As you can see, I'm converting a double to a String, then assigning that value to textResult (String). I formatted it properly to display decimals, but I can't figure out how to show as currency instead.
Based on what i've found online, it looks like I may have to use
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
and then use nf.format() somehow but it just doesn't work for me. Any guidance would be greatly appreciated.
public void onCalculateDealOne(View v) {
//get values from text fields
EditText priceEntry = (EditText) findViewById(R.id.etListPriceDealOne);
EditText unitsEntry = (EditText) findViewById(R.id.etNumberOfUnitsDealOne);
EditText couponEntry = (EditText) findViewById(R.id.etCouponAmountDealOne);
//get value from result label
TextView result = (TextView) findViewById(R.id.perUnitCostDealOne);
//assign entered values to int variables
double price = Double.parseDouble(priceEntry.getText().toString());
double units = Double.parseDouble(unitsEntry.getText().toString());
double coupon = Double.parseDouble(couponEntry.getText().toString());
//create variable that holds the calculated result and then do the math
double calculatedResultDealOne = (price - coupon) / units;
//convert calculatedResult to string
String textResult = String.format("%.3f", calculatedResultDealOne);
result.setText(textResult + " per unit");
dealOneValue = calculatedResultDealOne;
//hide the keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
//make deal one label visible
result.setVisibility(View.VISIBLE);
}
There are two simple solutions to this. You can use a DecimalFormat object, or you can use a NumberFormat object.
I personally prefer a Decimalformat object because it gives you more precise control over how you would like to format your output value/text.
Some may prefer the NumberFormat object because the .getcurrencyInstance() method is easier to understand than a cryptic string format (e.g. "$#.00", "#0.00").
public static void main(String[] args) {
Double currency = 123.4;
DecimalFormat decF = new DecimalFormat("$#.00");
System.out.println(decF.format(currency));
Double numCurrency = 567.89;
NumberFormat numFor = NumberFormat.getCurrencyInstance();
System.out.println(numFor.format(numCurrency));
}
The output for this example program is below:
$123.40
$567.89
You need to use formatter to format the double value you want, eg:
double money = 202.2
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String moneyString = formatter.format(money);
System.out.println(moneyString);

Rounding a number with printf in java?

i am trying to use System.out.printf to round a very large number to 2 decimal places. This is the code i am using:
System.out.printf(" %1.2f = overpayment:$" + overpayment);
I am getting this error:
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%1.2f'
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
I am under the impression that %f is the format specifier and %1.2f is used for a floating point number with 2 digits after the decimal.
I am trying to round 4.4260494195128784E-4 to 4.43. Thank you
Since I am getting under a cent for my overpayment, I think i have the wrong formula to calculate it. Does anyone have an idea on how to attain overpayment of a loan? The overpayment value should be 4.43. Here is my code:
import java.util.Scanner;
public class CreditCardPayoff {
public static void main(String[] args) {
// TODO Auto-generated method stub
double principle;
double annualInterestRate;
double monthlyPayment;
double numerator;
double denominator;
double monthsToPayOff;
double monthsToPayOffCeiled;
double totalAmountPaid;
double totalInterestPaid;
double overpayment;
Scanner keyboard = new Scanner(System.in);
principle = keyboard.nextDouble();
annualInterestRate = keyboard.nextDouble();
monthlyPayment = keyboard.nextDouble();
numerator = Math.log(monthlyPayment) - Math.log(monthlyPayment-
(annualInterestRate / 1200.00) * principle);
denominator = Math.log((annualInterestRate/1200.00) + 1.0);
monthsToPayOff = numerator/denominator;
monthsToPayOffCeiled = Math.ceil(monthsToPayOff);
totalAmountPaid = monthsToPayOffCeiled * monthlyPayment;
totalInterestPaid = totalAmountPaid - principle;
overpayment = (monthsToPayOffCeiled - monthsToPayOff)/monthlyPayment;
System.out.println("Principle:" + principle);
System.out.println("Annual Interest Rate:" + annualInterestRate);
System.out.println("Monthly Payment:" + monthlyPayment);
System.out.println("Months Needed To Pay Off:" + (int)monthsToPayOffCeiled);
System.out.println("Total Amount Paid: $" + totalAmountPaid);
System.out.println("Total Interest Paid: $" + totalInterestPaid);
System.out.printf("overpayment: $%1.2f ", overpayment);
}
}
My method to calculate overpayment, obtain difference between monthsToPayOff and monthsToPayOffCeil (ceiling) then divide by monthly payment. This got me 4.4260494195128784E-4.
In order to use String.format you do not concatenate the values for the placeholders with the format string, but rather pass them as parameters:
System.out.printf("overpayment: $%1.2f", overpayment);
printf takes one argument for every format specifier (see documentation). In Java arguments are separated by commas (,).
So, in your example, instead of a + that concatenate two strings (a string and a number into a string, to be precise), you should use a comma:
System.out.printf(" %1.2f = overpayment:$", overpayment);
That is not how you use printf.
System.out.printf("%1.2f and %d", 1.25f, 1000);
Knowing this, you can also add extra formatting:
printf( "$%.2f", overpayed );
Inside of the format string you can specify your data types, and then each one is passed as an argument thereafter.

Adding a trailing 0 to my 0.1, 0.2 values, but not to my 0.25 values

I have a double value that is pulled in from an external method call. When a 0.6 value comes through, I want it to be changed into 0.60, but I don't wan't to put "0" at the end of my string or else it will make my 0.65 values 0.650.
I had a problem before where it displayed 1.95 as 195000001, but I have fixed this problem.
double convPrice = callMethod.totalPriceMethod(); //Calls value from external method and adds to local variable.
totalPrice = Double.toString(convPrice); //local variable is converted to String
totalPrice = String.format("£%.2f", totalPrice ); //Formatting is applied to String
totalPriceLabel.setText(totalPrice); //String is added to JLabel.
Any help would be greatly appreciated.
Simply use String.format format specifier for floating point numbers:
String.format("%.2f", yourNumber)
Tutorial at: Formatting tutorial.
Or use a DecimalFormat object.
e.g.,
String s = String.format("%.2f", 0.2);
System.out.println(s);
Don't convert double to String pre-formatting as that's what the formatting is for. You're doing this
double convPrice = callMethod.totalPriceMethod();
totalPrice = Double.toString(convPrice);
totalPrice = String.format("£%.2f", totalPrice );
totalPriceLabel.setText(totalPrice);
When you want to do something like this:
double convPrice = callMethod.totalPriceMethod();
// totalPrice = Double.toString(convPrice); // ???????
totalPrice = String.format("£%.2f", convPrice);
totalPriceLabel.setText(totalPrice);
Since you're converting to currency, perhaps even better is to use a NumberFormat currencyInstance.
e.g.,
NumberFormat currencyInstance = NumberFormat.getCurrencyInstance(Locale.UK);
double convPrice = callMethod.totalPriceMethod();
totalPriceLabel.setText(currencyInstance.format(convPrice));

String returning a float with one decimal place

I'm trying to format my decimal to show only one decimal place. In my testprogram I set gpa to 3.5454 and it is returning to me the value 3.5454. How do I format it to show 3.5. I tried the code below and it doesn't work. I also tried it in my setGpa method and still no luck
/**
* This method return the student's gpa
* #return This student's gpa
*/
public float getGpa(){
NumberFormat formatter= new DecimalFormat("#0.0");
formatter.format(gpa);
return gpa;
}
Solved! - I just needed to cast type it (float) ((int)(gpa*10) / 10)
You're returning the float again. Maybe you instead wanted to
round the float instead of format it
return the String from formatter.format(gpa)
I think you should try following solution
public static String getGpa(){
NumberFormat formatter= new DecimalFormat("#0.0");
String format = formatter.format(gpa);
return format;
}
Solved! - I just needed to cast type it (float) ((int)(gpa*10) / 10)

Categories