Java double input - java

I am trying to let the user freedom of entering a number at his own style like he can choose to enter 2 or 2.00 but as you know the double cannot accept this (2). i want the double to accept this with 2 decimal places only (basically i am representing money).
this is what i am not sure how to take the input and convert that in to the 2decimals format. New to java.tks
Tried google but cant find where i can format at the input itself, means dont even let the user type any more decimal places other than 2decimal places, not post-process after entered in to multiple different variables., tks
public static void add()
{
double accbal;
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Enter account balance");
accbal = sc.nextDouble();
//this is the part where i need to know the entered value is formated to only 2 decimal places
}

Since showing decimal places is really a formality to the end user, you could read your value in as a String instead and convert it to a Double or BigDecimal, the latter being preferred if you're working with actual finances.
Related: What Every Computer Scientist Should Know About Floating-Point Arithmetic
public static void add() {
BigDecimal accbal; // could declare a Decimal
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("Enter account balance");
accbal = new BigDecimal(sc.nextLine());
System.out.println(df.format(accbal.doubleValue()));
}

Try this:
DecimalFormat df = new DecimalFormat ("#.##");//format to 2 places
accbal = sc.nextDouble();
System.out.print(df.format(aacbal));//prints double formatted to 2 places
however I see you say:
Tried google but cant find where i can format at the input itself,
means dont even let the user type any more decimal places other than
2decimal places
If the above is your intention for whatever reason then simply read in the input using nextLine() and then check to make sure after the decimal point it only has a length of 2:
double accbal=0;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter account balance");
String s = sc.nextLine();
if (s.substring(s.indexOf('.') + 1).length() <= 2)//accept input and convert to double
{
accbal = Double.parseDouble(s);
break; //terminates while loop
} else {
System.out.println("Incorrect input given! Decimal places cant exceed 2");
}
}
System.out.println("Balance: "+accbal);

If you want to accept input of the form "#.##" just specify a custom regex for Scanner.hasNext :-)
final Scanner input = new Scanner(System.in);
final Pattern pattern = Pattern.compile("\\d+\\.\\d{2}?");
while (input.hasNext()) {
System.out.println((input.hasNext(pattern) ? "good" : "bad")
+ ": " + input.nextDouble());
}
Using the following input:
2.00
3.14159
2
The result is: (also found here)
good: 2.0
bad: 3.14159
bad: 2.0
This way allows you to verify they enter an amount with two decimal places.
Even though you said you do not want a mere post-processing solution, in case you already have an amount and wish to convert it to use 2 decimal places, and you're focused on precision (since this is money), maybe try using BigDecimal -- in particular, see BigDecimal.setScale:
while (input.hasNextBigDecimal()) {
System.out.println(input.nextBigDecimal().setScale(2, RoundingMode.HALF_UP));
}
The output is thus:
2.00
3.14
2.00

Related

Bigdecimal userinput or double to Bigdecimal

I am creating a Currency converter using BigDecimal and now I am suck with an issue.
I have a user-defined number - "Amount" (this is the amount of currency you want to convert)
I am putting that userValue through the scanner class but I have only ever done this successfully with the following :
int userInput = new scanner.nextint();
I would have loved userinput to be passed as a BigDecimal
but my understanding of java is very limited.
would you suggest converting the double to BigDecimal or is there a much simple way.
If you would like to get user input as a BigDecimal then you can use one of Scanner class method nextBigDecimal() To convert existing double to BigDecimal you can use BigDecimal.valueOf() method.
Code sample:
public static void main(String[] args) {
var scanner = new Scanner(System.in);
System.out.println("Enter BigDecimal");
var number = scanner.nextBigDecimal();
System.out.println("BigDecimal from user input: " + number);
var doubleNumber = 2.15;
var decimal = BigDecimal.valueOf(doubleNumber);
System.out.println("Double converted to BigDecimal: " + decimal);
}
Listing:
Enter BigDecimal
2,15
BigDecimal from user input: 2.15
Double converted to BigDecimal: 2.15
Process finished with exit code 0
Keep in mind that while converting double to BigDecimal you may loose some accuracy of data, because double is less accurate comparing to BigDecimal.

Why do I get wrong mathematical results when using scanner class and delimiters for getting a double in Java?

I am writing a program where I have to get a user input, saved as a double. The user must be able to put it using both ',' and '.' as a delimiter - however they want. I tried using useDelimiter which works only partially - it does indeed accept both values (e.g 4.5 and 4,5) but when I later use the entered value in a mathematical equation, I get wrong results - it seems to round the user input down to the closest integer and as an effect no matter whether I enter, 4 or 4.5 or 4,5 or 4.8 etc., I get the same result, which is actually only true to 4.
Does anyone happen to know why it doesn't work?
double protectiveResistor=0; //must be a double, required by my teacher
double voltage= 5;
System.out.println("Please provide the resistance.");
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
protectiveResistor=sc.nextDouble();
}
catch(InputMismatchException exception)
{
System.out.println("Wrong input!");
System.exit(1);
}
if (protectiveResistor<0){
System.err.println("Wrong input!");
System.exit(1);
}
double current = (double)voltage/protectiveResistor;
double power = (double)current*current*protectiveResistor;
Thank you!
The useDelimiter method is for telling the Scanner what character will separate the numbers from each other. It's not for specifying what character will be the decimal point. So with your code, if the user enters either 4.5 or 4,5, the Scanner will see that as two separate inputs, 4 and 5.
Unfortunately, the Scanner doesn't have the facility to let you specify two different characters as decimal separators. The only thing you can really do is scan the two numbers separately, then join them together into a decimal number afterwards. You will want to scan them as String values, so that you don't lose any zeroes after the decimal point.
What useDelimiter() does is split the input on the specified delimiter.
As an example, if you have the input of 4,5, the following code will print "4".
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
If you also want to print the second part, after the ',', you need to add another line to get the next value, which would in this example print
"4
5":
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
System.out.println(sc.next())
In your code you can do it like this:
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
String firstPart = "0";
String secondPart = "0";
if (sc.hasNext()) {
firstPart = sc.next();
}
if (sc.hasNext()) {
secondPart = sc.next();
}
protectiveResistor = Double.parseDouble(firstPart + "." + secondPart)
}
// Rest of your code here
What this code does is split the input on whitespace, '.' and ','. For a floating point value you expect one part before the decimal point and one after it. Therefore, you expect the scanner to have split the input in two parts. These two parts are assigned to two variables, firstPart and secondPart. In the last step, the two parts are brought together with the '.' as decimal point, as expected by Java and parsed back into a variable of type Double.

Why is nextDouble() from the Scanner method sending me "Exception"

I'm suppose to enter 2 numbers, one int that is the amount to withdraw and one double which is the balance (with a space between them). Since every withdraw charges a fee of 0.5, balance must be a double. And thats what must be printed.
I get error at nextDouble, why? I have just 1 month coding, I thought this was going to be a piece of cake, I think BASIC syntax ruined me 30 years ago :(
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//init variables
int amount;
double balance;
//insert amount and balance
Scanner input = new Scanner (System.in);
amount = input.nextInt();
balance = input.nextDouble();
//reduce amount+fee from balance
balance=balance-(amount + 0.50);
//print new balance
System.out.print(balance);
input.close();
}
}
It is dependant on Locale, try to use comma instead of a dot or vice versa.
Ex: 1,5 instead of 1.5
You can check, if there is some int or double to read.
And you have to use , or . depending on the country, you are.
If you need it country independent, read it as string and parse then (see below)
A solotion would be to read the line as a string and parse it then to int and double.
Checking if double is available:
input.hasNextDouble();
Read as String:
String line = input.nextLine();
String[] sl = line.split(" ");
amount = Integer.parseInt(sl[0]);
balance = Double.parseDouble(sl[1]); //solve the problem with . and ,
You also could check if there are enough inputs.

Rounding Decimals in Java

So, I was making a program, where I have the user insert a numerator and denominator, the program converts the pseudo-fraction, to a decimal. It works fine, just one thing. One, if I enter a fraction that is a repeating decimal, (ex. 1/3, 0.3333333...), I want either it say 0.33 repeat, or for irrational numbers, It would round it after let's say 7 digits, and then stop and have "... Irrational" after. How could I do this? Code is below.
package Conversions;
import java.util.*;
public class FractionToDecimal {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
if (denominator == 0) {
System.out.println("Can't divide by zero");
}
else {
double fraction = (double)numerator / denominator;
System.out.println(fraction);
}
}
}
You could use this:
DecimalFormat df = new DecimalFormat("#.######");
df.setRoundingMode(RoundingMode.CEILING);
Add as many # as you want decimals and then ou can simply use it like this:
Double d = 12345.789123456;
System.out.println(df.format(d));
Using three # would give you for the example above: 12345.789 for instance.
Please note that you can pick your rounding mode of course.
Small other note: Next time you ask a question on SO, please show some research, there are thousands of post about this and thousands of tutorials online. It would be nice to show what you have tried, what doesn't work ...

JAVA: use entered integer to define decimal places

this is my first entry to stackoverflow so please let me know if something is wrong.
I know how to show an imported float number with x decimal numbers. But how do you define the amount of decimal numbers via a new scanned int number?
This is my code: (of course "%.decimalf" doesn't work, I just wanted to test it)
anyone? thanks in advance!
import java.util.Scanner;
public class Fliesskommazahl{
public static void main (String[] args){
// ask for/import floating point number
System.out.println("Please enter a floating point number like 1,1234: ");
Scanner scanner = new Scanner(System.in);
float number = scanner.nextFloat();
// show floating point number
System.out.println("You've entered: " + number);
/* show number with exactly two decimal places
In short, the %.02f syntax tells Java to return your variable (number) with 2 decimal places (.2)
in decimal representation of a floating-point number (f) from the start of the format specifier (%).
*/
System.out.println("Your number with two decimal places: ");
System.out.printf("%.02f", number);
System.out.println();
// import second (positive) number.
System.out.println("Please enter a positive integer number to define amount of decimal places: ");
Scanner scanner2 = new Scanner(System.in);
int decimal = scanner.nextInt();
// show imported floating point number with imported number of decimal places.
System.out.printf("%.decimalf", number);
}
}
This could work
System.out.printf ("%." + decimal + "f", number);
You should use this class I think this could work out really good for you here it is:
double num = 123.123123123;
DecimalFormat df = new DecimalFormat("#.000");
System.out.println(df.format(num));
In this case the output would be 123,123, the amount of zeros after the #. is the amount of numbers you want after the dot.

Categories