How to round a user input in Java - java

I'm attempting to get a user input of a decimal, then round it to two decimal points. This is the code I currently have which is not working correctly, and I'm not sure why.
package code;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class DecimalPlaces {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);
Scanner qweInput = new Scanner(System.in);
System.out.println("Enter a decimal number:");
String qwe1 = qweInput.next();
df.format(qwe1);
System.out.println(qwe1);
}
}

With scanner, better use nextLine() when you can do it, it preserves from errors with the return line char:
String qwe1 = qweInput.nextLine();
Then you need to parse to double, because if not it tries to cast from Object to double and it crashes
df.format(Double.parseDouble(qwe1));
Then the format method return the string formated, because String are immutable, so you need to print direclty or save it :
qwe1 = df.format(Double.parseDouble(qwe1));
System.out.println(qwe1);
//----------------------------------OR----------------------------------
System.out.println(df.format(Double.parseDouble(qwe1)));
Edit : to avoid parsing to Double you can use nextDouble() from Scanner, as it it would direclty save as a double, but to save the format you would need another String so, with proper name ;)

Instead of
String qwe1 = qweInput.next();
try
double qwe1 = qweInput.nextDouble();
By the way, qwe1 is a terrible name for a variable! Variable names should reflect what they are for.

I would suggest getting the user input as a double and then do this:
double roundNum = Math.round(num * 100.0) / 100.0;

Related

String to BigDecimal value

Can someone help me getting the exact value to BigDecimal?
My code is as below,
import java.math.BigDecimal;
public class HelloWorld{
public static void main(String []args){
String x="2.7955814565E10";
BigDecimal y=new BigDecimal(x);
System.out.println(y.toPlainString());
}
}
My actual value in the DB is 27955814565.0, a String. I read this string from DB and set it in a bean class where the amt field has type string, using the value "2.7955814565E10". When I try to convert this to a BigDecimal I get 27955814565 instead of 27955814565.0.
Can someone tell me what is the issue because for rest all fields the logic for converting the string value to BigDecimal is working fine and I want the exact value as in DB?
The BigDecimal doesn't infer extra digits in this case.
If the input is
String x = "2.79558145650E10"; // note the extra 0
you get the expected result. You can also add the digit as required.
String x = "2.7955814565E10";
BigDecimal y = new BigDecimal(x);
if (y.scale() < 1)
y = y.setScale(1);
System.out.println(y.toPlainString());
prints
27955814565.0
BTW If your input is
String x = "2.7955814565000E10"; // note the extra 000
the output is
27955814565.000
As you already know, Your String is in scientific notation,
To translate these value into origional BigDecimal or Decimal we need a proper way.
public class Test {
public static void main(String[] args) {
double firstNumber = 12345678;
double secondNumber = 0.000012345678;
String firstNumberAsString = String.format ("%.0f", firstNumber);
String secondNumberAsString = String.format("%.12f",secondNumber);
System.out.println(firstNumberAsString);
System.out.println(secondNumberAsString);
}
}
output will be:
12345678
0.000012345678
You can use Format method as well on BigDecimal to achieve your goal.
DecimalFormat decimalFormat = new DecimalFormat("0.0000000000");

How to indent string and double results in Java?

My question concerns the indentation of the results specifically. Some are String and some double. So far I have the following java program shown at the below. I need the following result:
Name: Yoda Luca
Income: %5000.00
Interests: Swimming, Hiking
I don't want to have to write a prefix for every line. Is there a quicker way to format once for "String" and once for "Double" ?
Program:
import java.util.Scanner;
public class forTesting {
public static void main(String[] args) {
String prefixName = "Name:";
String prefixIncome = "Income";
String Name;
double Income;
//create a Scanner that is connected to System.in
Scanner input = new Scanner(System.in);
System.out.print("Enter name:");
Name = input.nextLine();
System.out.print("Enter income for period: ");
Income = input.nextDouble();
String format = "%-40s%s%n";
System.out.printf(format, prefixName,Name);
System.out.printf(format, prefixIncome, Income);
}
}
String format takes format and followed by n number of arguments.
Yes. %f is for double and you can write them in one shot.
String format = "%-40s%s%n%-40s%f%n";
System.out.printf(format, prefixName,Name,prefixIncome, Income);
And that gives you floating point double. To get it in standard format
How to nicely format floating numbers to String without unnecessary decimal 0?

number converting to other number

Hello I have a bit of a problem with calculating numbers from a file.
My input is the following rawData.txt:
19.95
5
The output however is this:
49.0 57
My code looks like this:
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.PrintStream;
class ReadAndWrite
{
public static void main(String args[])
throws FileNotFoundException {
Scanner diskScanner = null;
diskScanner = new Scanner(new FileReader("rawData.txt"));
PrintStream diskWriter = new PrintStream("cookedData.txt");
double total;
double unitPrice = diskScanner.findWithinHorizon(".", 0).charAt(0);
System.out.println(unitPrice);
int quantity = diskScanner.findWithinHorizon(".", 0).charAt(0);
System.out.println(quantity);
total = unitPrice * quantity;
diskWriter.println(total);
diskScanner.close();
}
}
Eventually the cookedData.txt file contains the number 2793.0
Please help
You are fetching only the first character of each line - because of the charAt(0), then cast it to a double (casting char to double!!)
I can't understand what you are trying to do, but converting char to double using casting is almost always NOT what you should do.
Try using Double.parseDouble instead. see it here: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)
diskScanner.findWithinHorizon(".",0).charAt(0);
means that you are getting any character, because the first parameter of findWithinHorizon is a regular expression, and "." means one character. From that string you take the first char, i.e. 1. The ascii value of 1 is... 49.

Java Seperate method to Convert double input to 2 decimal place

I have read many posts in this forum on converting user input to 2 decimal place.
However, I am required to write a method on its own and only be responsible for converting user input to 2 decimal places.
I am currently meeting an error of not being able to convert String to double when doing the decimal conversion.
Below is my current code.
public class LabQuestion
{
static double twoDecimalPlace (double usrInput){
DecimalFormat twoDpFormat = new DecimalFormat("#.##");
usrInput=twoDpFormat.format(usrInput);
return usrInput;
}
public static void main(String[] args)
{
System.out.print("Enter a number on a line: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
twoDecimalPlace("Current input ",d);
}
}
How may I be able to create a method that allows converting to 2 decimal place of a double input from user? Thank you.
You use a NumberFormat object such as a DecimalFormat object to convert a String to a number, which is called "parsing" the String or a number to a String, which is called "formatting" the number, and so you will need to decide which it is you would like to do with this method. It sounds like you want to change the display of the number to show a String representation with 2 decimal places, and so I think that your output should be a String. For example:
import java.text.DecimalFormat;
import java.util.Scanner;
public class NumberFormater {
static DecimalFormat twoDpFormat = new DecimalFormat("#0.00");
static String twoDecimalPlace(double usrInput) {
String output = twoDpFormat.format(usrInput);
return output;
}
public static void main(String[] args) {
System.out.print("Enter a number on a line: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
System.out.println("Output: " + twoDecimalPlace(d));
}
}
Try this:
public Double formatDouble(Number number){
return Double.parseDouble(String.format("%.3f", "" + number));
}

Java String to Double

I recently began to program in Java, and i ran into a little problem:
I already made a String to Double line, but it doesn't seems to work proberly. As you see, the string I want to convert into a Double is one of following: USD, GPB and EURO. I know you can't convert text into a Double, but I already told Java the values of the Strings.
When I run the program below, I get this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "usd" at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source) at java.lang.Double.parseDouble(Unknown Source) at Valuta.main(Valuta.java:22)
Why does that happen?
import java.util.Scanner;
public class Valuta {
public static void main(String[] args){
double euro, usd, gpb, done;
Scanner input = new Scanner(System.in);
euro = 7.46;
usd = 5.56;
gpb = 8.84;
System.out.println("DKK to ??");
System.out.println("USD,GPB or EURO?");
String temp = input.nextLine();
System.out.println("amount of dkk??");
Double dkk = input.nextDouble();
System.out.println("mhm");
double donee = Double.parseDouble(temp);
done = dkk*donee;
System.out.println(done);
I think what you want is to be able to associate user input for System.out.println("USD,GPB or EURO?"); to
euro = 7.46;
usd = 5.56;
gpb = 8.84;
One of hte ways to do it is to create a look up Map like this:
Map<String, Double> lookUpMap = new HashMap<String, Double>(){{
put("EURO", new Double(7.46));
put("USD", new Double(5.56));
put("GPB", new Double(8.84));
}};
Then parse user input and look up Double value:
lookUpMap.get(userInput)
The problem is you parse the currency as a double input. This line:
double donee = Double.parseDouble(temp);
should be select the proper conversion factor for the currency. You can do that with a simple if/else, a map or whatever:
double donee;
if ("usd".equalsIgnoreCase(temp) {
donee = usd;
} else if ("gbp".equalsIgnoreCase(temp)) {
donee = gbp;
/* more cases ... */
} else {
throw new RuntimeException("unknown currency");
}
You probably should move that up to before you get the number input, since if it causes an error the number input can't be processed anyway.
You have a couple of problems in this program. First to fix you're error you need to declare type double for the USD, GBP, and EURO variable names that you have there. Second you are going to need to do an if else if else block to determine what conversion to do.
double total;
if(temp.equalsIgnoreCase("USD")){
total = dkk*usd;
}else if(temp.equalsIgnoreCase("GBP"){
total = dkk*gbp;
}else {
total = dkk*euro;
}
System.out.println("This is your converted total " + total);
That will do the conversion that you want it to do. You should also take out Double.parseDouble(temp) because turning that string into a double isn't going to help you.

Categories

Resources