JAVA: use entered integer to define decimal places - java

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.

Related

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 double input

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

Making the output of an operation to display 2 decimal points

Here's my current code:
import java.util.Scanner;
public class Addition
{
// main method begins execution of Java application
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
int area;
int number1;
int number2;
System.out.print( "Input base value = " ); // prompt
number1 = input.nextInt(); // read first number from user
System.out.print( "Input height value = " ); // prompt
number2 = input.nextInt(); // read second number from user
area = 1/2*(number1*number2); // add numbers
System.out.printf( "The Area of the right triangle is %d\n", area ); // display sum
} // end method main
} // end class Addition
I would like to make it display the decimal point when i input 5 as the first and second number. i tried replacing int area with double area but doesn't work..
If you want two digits after the decimal point, you must make area a double and use a format string of %1.2f.
Example:
System.out.printf("%1.2f\n", 78785.7);
You can check out the vast array of examples here:
Formatting Numerical Data
Hope it helps :) Cheers!
In addition to making area a double, you'll also need to make at least one of the terms in 1/2*(number1*number2) a double, or you'll only be doing int math, which won't turn out how you expect. For example:
1.0/2*(number1*number2)
In your output, you'll also have to use %f instead of %d.

How to check how many Divisors there's in a whole number and How to express a factorial equation to Odd numbers?

So my homework tells me to write the equation for a ODD number, the equation must be a factorial if and only if the number is odd.
In my head I the structured came like this (until I don't know how to use the factorial)
import java.util.*;
public class apple {
public static void main(String args []) {
Scanner var = new Scanner(System.in);
int m;
System.out.println("Type in your first number: ");
m = var.nextInt();
if (m==0){ //i don't know if m==0 express the condition to be whole numbers, please tell me which is.
//here I need to check how many divisors there is for my statement
}else if //Again, i don't know how to proceed here, i need to place the condition if M is ODD, how?
//here i need to state (what i guess) the equation of factorial number (in which case, if and only if is odd)
// and than print the results out. That is all the job it needs to be done.
}
}
}
So it seems like you want to print out the factorial of a number if you have an odd number and the divisors of the number if it is even. You haven't specified a way to present the divisors, so here's one way you could do it:
Scanner var = new Scanner(System.in);
int m;
long x=1; //for the factorial, we want to store in a long to combat data overflow
System.out.println("Type in your first number: ");
m = var.nextInt();
//if the input is odd we calculate its factorial
if (m%2==1){
for (int i = 1;i<=m;i++)
x*=i;
System.out.println(m+"!: "+x);
}
else{
System.out.println("1 is a divisor for "+m);
System.out.println("2 is a divisor for "+m);
if (m%3==0)
System.out.println("3 is a divisor for "+m);
//and so on for more divisors of m
}
A first note, you need to add "throws IOException" after your close parentheses in the main declaration since you are asking the computer for input.
How to detect if a number is odd. x=number.
if(x%2==1)
//Then the number is odd
else
//The number is even
How to detect if the number is a whole number: whole meaning an integer greater than 0. You already know its an integer (Thats what you are asking for with nextInt().) so all you need to say is:
if(m>0)
//Then it is whole
Please clarify on anything this did not answer, your question was a bit vague.

IllegalFormatPrecisionException while trying to format string

I'm trying to write a program which prompts the user to enter two 3×3 matrices and displays their product.
For example, a user can enter:
Matrix A: 2 4 6 8 10 12 14 16 18
Matrix B: 1 2 3 4 5.6 6.6 7.4 8.1 9
Below is what I have tried, but I keep getting this error. Any help to point me in the right direction would be appreciated. I'm trying to get it to one decimal place:
Exception in thread "main" java.util.IllegalFormatPrecisionException: 2
at java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:2892)
at java.util.Formatter$FormatSpecifier.(Formatter.java:2643)
at java.util.Formatter.parse(Formatter.java:2480)
at java.util.Formatter.format(Formatter.java:2414)
at java.io.PrintStream.format(PrintStream.java:920)
at java.io.PrintStream.printf(PrintStream.java:821)
at Exercise6_25.main(Exercise6_25.java:55)
import java.util.Scanner;
public class matrixCalc
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
int i,j,k;
int n=3;
double a[][]= new double[n][n];
double b[][]= new double[n][n];
double c[][]= new double[n][n];
System.out.println("enter the array elements of a:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=s.nextDouble();
}
System.out.print(" ");
}
System.out.println(" ");
System.out.println("enter the array elements of b:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=s.nextDouble();
}
System.out.print(" ");
}
System.out.println(" ");
System.out.println("the result matrix is:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
for(k=0;k<n;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.printf("%.2d", c[i][j]+" ");
}
System.out.println();
}
}
}
You are using the %d specifier, which requires an integer argument -- but you are giving it a String (because c[i][j]+" " converts c[i][j] to String when concatenating it).
Also, the %d specifier does not use a decimal point at all. Since integral types can be implicitly converted to floating-point types, the %f specifier is what you're looking for.
And finally, the number after the decimal point in the format specifier is what tells it how many decimal places to go to. You say you only want one decimal place, so let's make that a 1.
So what we end up with is this:
System.out.printf("%.1f ", c[i][j]);
See the Formatter Javadocs for a (somewhat mind-boggling) description of the all possible format specifiers. (Don't worry too much if you can't understand everything there; you'll never need most of it anyway.)
You can't format integers by using a decimal point in the conversion. Since c[i][j] is a double, you can use a floating point conversion:
System.out.printf("%.2f ", c[i][j]);
Instead of:
System.out.printf("%.2d", c[i][j]+" ");
See the help page for the formatter syntax for more information.
Are you sure you meant to say "%.2d" in your printf rather than "%.2f"?
You usually only use d for integer values, you have doubles in your matrix.
Your error is probably here:
System.out.printf("%.2d", c[i][j]+" ");
Check the documentation of how values are formatted when printed out.

Categories