This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
After some awesome help yesterday on this site, I am back with another question. I have my input/output equation the way I want it but need help rounding the decimal off to the hundredths position. The way it is set up now the output of pounds seems to just repeat the answer. I have been inputting 10.2 as the weight in kilograms and the answer I keep receiving in pounds is 22.4422.44. I know it is something with the String.format I am using but after messing with it for quite a while I can't seem to figure it out. I know it is something silly but I have been working on this for a while now and I think my brain may be mush. Below is my program.
//This program converts kilograms to pounds using input/output dialog boxes.
import javax.swing.*;
public class SNHU2_3 {
public static void main (String[] args){
String inputStr;
String outputStr;
double pounds;
double kilograms;
inputStr = JOptionPane.showInputDialog("Enter weight in kilograms");
kilograms = Double.parseDouble(inputStr);
outputStr = ("Kilograms = " + kilograms) + "\n" + ("Pounds = " + (kilograms * 2.2)) + String.format("%.2f", (kilograms * 2.2));
JOptionPane.showMessageDialog(null, outputStr, "Weight Conversion", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
You can just simply use:
kilograms = Double.parseDouble(inputStr);
Math.round(kilograms);
I suggest
outputStr = String.format("Kilograms = %.2f \n Pounds = %.2f", kilograms, (kilograms * 2.2));
I would first of all suggest that you should thoroughly research your question before posting it. There are many related question that are already asked in this forum. Also study a little bit more about String.format.
Next to explain your problem:
outputStr = ("Kilograms = " + kilograms) + "\n" + ("Pounds = " + (kilograms * 2.2)) + String.format("%.2f", (kilograms * 2.2));
What this statement does is it concatenates different strings that you have placed between '+' signs. So we start from the left where your have the String "Kilograms = " so first it is taken then we have kilogram this is basically a double and in your example stores the value 10.2. Now the String becomes "Kilograms = 10.2". After that you have the string "\n". So the string becomes "Kilograms = 10.2\n". Then you have "Pounds = ", so on concatenation the string becomes "Kilograms = 10.2\nPounds = ". After that it hits the expression (kilograms * 2.2) Which in your case is 10.2*2.2 which computes to 22.44 So after concatenation the string becomes "Kilograms = 10.2\nPounds = 22.44". After that it hits String.format("%.2f", (kilograms * 2.2)). The return value of this expression in your case is '"22.44"'. So now the finally concatenated string is "Kilograms = 10.2\nPounds = 22.4422.44" which is finally stored in outputStr. And this is exactly what you get.
I believe that I have been able to explain you what is the problem. SO REMEMBER - you should thoroughly research your question before posting it.
Related
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 1 year ago.
I want to remove zeroes from my string as decimal places, but I am not able to do that. Also, I want the decimal places gone only if zeros are there else the decimal places will be there.
Example:
1234.00 should become 1234
1234.25 should remain 1234.25
Here is the code I am using to do that but its not working.
String price_normal2 ="1234.00";
if(price_normal2.contains(".00")){
price_normal2.replace(".00","");
Log.i("PRICEEEEE",""+price_normal2);
}
Please help me in this.
String class are immutable, So replace method will not replace the value in same object instead it will return the new string which can you store it into another object or the same object by assigning it.
String price_normal2 ="1234.00";
if(price_normal2.contains(".00")){
price_normal2 = price_normal2.replace(".00","");
Log.i("PRICEEEEE",""+price_normal2);
}
Parse the price to double to ensure the validity and then convert it to integer
public static void main(String[] args) {
String price_normal2 = "1234.00";
double priceWithFraction = Double.parseDouble(price_normal2);
int price = (int) priceWithFraction;
System.out.println("Price " + price);
}
check this one it will remove the decimal part if it all are zero or remove the any zero on the left side
NumberFormat numberFormat = DecimalFormat.getNumberInstance();
numberFormat.setMinimumFractionDigits(0);
System.out.println(numberFormat.parse("1234.001"));
is it fine with you that 1234.40 be 1234.4 or you want it to be 1234.40?
you can use DecimalFormat class
DecimalFormat decimalFormat = new DecimalFormat("00.##");
String formatted = decimalFormat.format(Double.parseDouble("1234.30"));
String[] splitted = formatted.split("\\.");
if (splitted.length > 1) {
String dec = (splitted[1].length() == 1) ? splitted[1] + "0" : splitted[1];
formatted = splitted[0] + "." + dec;
}
logs
D/mridx: main: 1234.30
I'm taking my java class, and I'm working on a Tsubo calculator for my assignment. I don't usually ask questions on stack overflow so forgive me if this seems basic. I've done some searching here and tried some of the solutions but none have worked in my case. I'm going to copy just part of my conversion below
```
System.out.println("You have chosen to convert square feet to Tsubo");
System.out.println("Please enter the total sqft you are looking to convert");
sqftInput = keyboard.nextInt();
// Double is converted to string so out put remains an object of the same data type
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + sqftResultAsString + " Tsubo"); `
When I do this, it tells me I can't format a double that the type is not applicable to arguments for DecimalFormat.
When I change it to look like this (offending line is commented out)
' System.out.println("You have chosen to convert square feet to Tsubo");
System.out.println("Please enter the total sqft you are looking to convert");
sqftInput = keyboard.nextInt();
// Double is converted to string so out put remains an object of the same data type
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
//sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + sqftFormatted + " Tsubo");
The program compiles and runs, and when I use 5238 as an input number, then my output looks like this --> 5238.0 is equal to :java.text.DecimalFormat#674dc Tsubo
instead of actually displaying the answer which is 325.07.
I've also tried using some regex formatting using the stringFormat but i wind up getting illegalformatting exception.
Long story short, What I'm trying to achieve is an output that is formatted to 2 decimal places, and then converted to a string that the system outputs as an answer. What am I missing? Is this Decimal Format automatically converting this to a string object?
DecimalFormat is used to produce a formatted String. If you print it directly, it will show its (kind of, it's called idenity hashcode) memory address cause that is what the DecimalFormat.toString() does.
Instead, you should use it to produce your output string and print that directly.
As follows:
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
String out = sqftFormatted.format(sqftResult); // or whatever you want to print
//sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + out + " Tsubo");
See docs for more details
I want to take a number the user enters and multiply it by a couple of different numbers I set but I can't figure out how to declare an integer and get it to play nicely with whatever number the user enters. I've tried writing
System.out.println("If you take" + stepsOne * firstNum + "steps in a 10 second interval, you could potentially achieve...");
and just about every variation I can think of but I keep getting error messages. Apparently javac hates me for some reason. :/
Also, whenever the greeting displays, there's no space between the data the user enters and my system.out.println stuff so if they enter the name "George" it comes out as "HelloGeorge". Not as big of an issue as the above but if you know how to fix that then have at it. :)
Here's my code:
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
Scanner userInputScanner = new Scanner(System.in);
int firstNum;
firstNum = 6;
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine();
System.out.println ("Hello," + userName + ". How many steps do you take in a ten second interval?");
String stepsOne = userInputScanner.nextLine();
System.out.println("If you take" + stepsOne + "steps in a 10 second interval, you could potentially achieve...");
System.out.println ("Number of steps per minute:");
System.out.println ("Number of steps per hour:");
}
}
There is a crucial difference between the string 123 and the integer 123 - the first is merely a sequence of characters, which have no mathematical meaning. You need to parse the string, meaning that you must construct an integer based on the characters of the string. There's a built-in method for this (although it's very interesting to do it yourself too): Integer.parseInt().
String stepsOneString = userInputScanner.nextLine();
int stepsOne = Integer.parseInt(stepsOneString);
Now, stepsOne is an integer on which you can perform mathematical operations. However, Integer.parseInt() throws an exception that you'll need to handle. At this point in your course, I'm guessing that you're expected to use the built-in conversion capabilities of the Scanner:
int stepsOne = userInputScanner.nextInt();
This will essentially perform the two above steps for you.
I strongly recommend that you read up on the subject of data types, which will explain the above concepts.
Once you have a string representing a number, you can use Integer.parseInt() to get an integer from it.
String stringSteps = userInputScanner.nextLine();
int steps = Integer.parseInt(stringSteps);
Here is a complete program with improved spacing.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine(); //Asks user name
System.out.println("Hello, " + userName +
". How many steps do you take in a ten second interval?");
String stringSteps = userInputScanner.nextLine();
int steps = Integer.parseInt(stringSteps);
System.out.println("If you take " + steps +
" steps in a 10 second interval, you could potentially achieve...");
System.out.println ("Number of steps per minute: " + (6 * steps));
System.out.println ("Number of steps per hour: " + (60 * 6 * steps));
}
}
Basically, I just want to take a number the user enters and multiply it by a couple of different numbers I set but I can't figure out how to declare an integer and get it to play nicely with whatever number the user enters. I've tried typing
First problem is stepsOne is String, so it can't be used to perform arithmetic on (at least not they type you're trying). So you need to convert it to a int
int stepsOneInt = Integer.parseInt(stepsOne);
nb: This will throw a NumberFormatException if the String can't be converted to a int value, so beware of that
Now you can use it to perform other arithmetic tasks
System.out.println("If you take " + (stepsOneInt * firstNum) + " steps in a 10 second interval, you could potentially achieve...");
Also, whenever the greeting displays in javac, there's no space between the data the user enters and my system.out.println stuff so if they enter the name "George" it comes out as "HelloGeorge". Not as big of an issue as the above but if you know how to fix that then have at it. :)
That's because you don't add any spaces before you print the value
System.out.println ("Hello, " + userName + ". How many steps do you take in a ten second interval?");
Not sure to understand your issue...
You can't do stepsOne*firstNum as stepsOne is a String.
If stepsOne must be an int, just do this:
int stepsOne = userInputScanner.nextLine(); //Asks user a nb
I'm a newby java guy trying to get my print out statement to format decimal placements.. I know that %.2f works, but for whatever reason when I try to apply the %.2f it bombs.... Not sure what to do.. any advice? thanks in advance!
credits = int
raise = double
System.out.printf("An undergraduate resident student taking " + credits + " currently pays $" + "%,.2f",credtotal);
System.out.println("\n");
System.out.printf("with a increase in tuition of " + (trying to format here) raise + ", per credit will become " + raisecredund + ", and an undergraduate resident taking " + credits + " credits" + " will pay $" +"%,.2f",(credits*(raise*245.73))+ credtotal);;
You appear to be using "%,.2f" with a comma which I don't think is legal. %.2f will print the number to 2 decimal places.
If you want to include a comma ever 3 places like in money you should use a DecimalFormat
DecimalFormat formatter = new DecimalFormat("#,###.00");
final String str1 = String.format("An undergraduate resident student taking %d currently pays $%.2f",credits, credtotal);
EDIT: I didn't notice that you were using printf. You were close:
System.out.printf("An undergraduate resident student taking %d currently pays $%.2f", credits,credtotal);
Using your first example string, you supply the formatting characters inline and then provide an argument for each placeholder. Assuming credtotal is a double and knowing credits is int, the above would yield (with respective values assigned)
An undergraduate resident student taking 1 currently pays $2.00
See creating formatted strings section.
I have a problem the output is supposed to be double but instead it is string
I am trying to add two double values but it is giving it as a string. I am using eclipse. Currently the program is compiling and running. If anyone have a moment I would appreciate it.Cheers guys. Here is the source code.
import java.util.Scanner;
public class FutureInvestment
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter investment amount: ");
double investmentAmount = input.nextDouble();
System.out.println("Enter monthly interest rate: ");
double monthlyInterestRate = input.nextDouble();
System.out.println("Enter number of years: ");
int numberOfYears = input.nextInt();
double futureInterestValue = investmentAmount * ( Math.pow((1 + monthlyInterestRate), numberOfYears * 12));
System.out.println("Accumulated value is: " + futureInterestValue + investmentAmount);
}
}
You need to format your output. You can use DecimalFormat or you can try the String#format function:
System.out.println(
String.format("Accumulated value is: %.2f",
futureInterestValue + investmentAmount));
So you can get the 2 decimal output. Plus, I recommend to create a variable with your result, so you can turn your code into
double accumulatedValue = futureInterestValue + investmentAmount;
System.out.println(
String.format("Accumulated value is: %.2f", accumulatedValue);
Since you're doing it in a println, it's doing string concatenation. If you want to add the double's together, you need to group them using ().
Try
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
double accumulatedValue = futureInterestValue + investmentAmount;
System.out.println("Accumulated value is: " + accumulatedValue);
Try this.
You were getting String as result of concatenation, since anything concatenated to a string is converted to string. Therefore, you need to complete the value beforehand as I shown above, or you need parentheses.
I think change it to this would work:
double futureInterestValue = investmentAmount * ( Math.pow((1 + monthlyInterestRate / 100), numberOfYears * 12));
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
you are missing some brackets, so your statement gets executed from left to right, thus appending the double to the string. You would need something like:
System.out.println("Accumulated value is: " + (futureInterestValue +
investmentAmount));
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
After the first +, Java has concatenated the first string with the first double, resulting in a string. Then it does another concatenation with the second double. You need to calculate the result first before making a string out of it.
When two operators could be evaluated within a line of code, they do so with a fixed precedence. While this example has been explained by many, you might want to review all of the precedence rules.
You can try:
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
or add a variable like double accumulatedValue=futureInterestValue + investmentAmount;
and then System.out.println("Accumulated value is: " + accumulatedValue);
The problem is your number is getting way too large, and Java switches over to scientific notation when printing the value.
If your monthly interest rate is entered as 4.25 (meaning 4.25%), you have to convert that to the correct decimal representation of 0.0425 before using it in your calculations - you have to divide it by 100. If you don't, the interest rate used will be much larger than you intended; in this case 425%.
In other words, change
double monthlyInterestRate = input.nextDouble();
to
double monthlyInterestRate = input.nextDouble()/100;