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 ...
Related
If the number of digits is infinite then I mark it as irrational and everything else is rational as it would be finite.
I tired input 3.14 but it crashed and didn't compile the output of irrational or rational.
import java.math.BigDecimal;
import java.util.Scanner;
public class non_terminating_decimals {
public static void main(String[] args) {
Scanner inputNumber = new Scanner(System.in);
System.out.println("input number : ");
BigDecimal inputnumber = inputNumber.nextBigDecimal();
BigDecimal numerofDigits = input(new BigDecimal(String.valueOf(inputnumber)));
BigDecimal infinity = BigDecimal.valueOf(Double.POSITIVE_INFINITY);
if (numerofDigits == infinity) {
System.out.println("Irrational");
}
else {
System.out.println("Rational");
}
}
static int integerDigits(BigDecimal number) {
return number.signum() == 0 ? 1 : number.precision() - number.scale();
}
static BigDecimal input(BigDecimal number) {
return BigDecimal.valueOf(0);
}
}
Let's unpack this statement:
BigDecimal infinity =
BigDecimal.valueOf(Double.POSITIVE_INFINITY);
Double.POSITIVE_INFINITY is some number.
Looking at the documentation for BigDecimal.valueOf, we see it uses Double.toString() to do the conversion.
Looking at the documentation for that, we see that a value of positive infinity results in the string "Infinity".
Thus, we're effectively left with trying to evaluate
BigDecimal("Infinity");
And if we look at the documentation for that particular constructor, there's no suggestion it can handle non-numeric string arguments.
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.
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
import java.util.Scanner;
class Calculator
{
public static void main(String args[]){
Scanner mortgage = new Scanner(System.in);
System.out.println(mortgage.nextLine());
double iRate;
double lAmount;
double answer;
System.out.println("Enter interest rate");
iRate = mortgage.nextDouble();
System.out.println("Enter loan amount");
lAmount = mortgage.nextDouble();
answer = iRate + lAmount;
System.out.println(answer);
}
}
My question is I don't think I am declaring the double correctly and am getting an error. How do I declare the double correctly so the program runs without error
That code compiles fine although:
System.out.println(mortgage.nextLine());
seems a bit strange since you wait for a line then print it out. Not sure why you would want to do that.
The following code with that line removed and some cosmetic changes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner mortgage = new Scanner (System.in);
double iRate, lAmount, answer;
System.out.println ("Enter interest rate");
iRate = mortgage.nextDouble();
System.out.println ("Enter loan amount");
lAmount = mortgage.nextDouble();
answer = iRate + lAmount;
System.out.println ("Answer is " + answer);
}
}
outputs:
Enter interest rate
10
Enter loan amount
50000
Answer is 50010.0
You may also want to rethink the way in which you do interest rate calculations. Anyone who's ever done work for a bank would get a giggle out of that.
The general way to calculate the interest due on some capital for a given percentage rate would be something like:
answer = iRate / 100.0 * lAmount;
although I realise you may have intended to clean that up once you get past your immediate problem, so apologies for that friendly jab :-)
I'm having to guess since you didn't specify the error, but it's likely coming from your usage of mortgage.nextDouble();. nextDouble(); will read JUST the next double from the line you type in, meaning there will be a trailing newline character at the end, which will result in it behaving in ways you don't expect.
There's a few alternative ways to go about it, so I'll just show one here:
double iRate;
iRate = Double.parseDouble(mortgage.nextLine());
Mind you, this does as much sanity checking as your code (as in, none!). What this does is read in a line of input, and then have the Double class convert the resulting String into a Double, which is stored in the double iRate.
If you want your "Enter interest rate" line to appear first, remove System.out.println(mortgage.nextLine());; it's not doing anything. Your program is waiting for an input before it can proceed, which I think was your problem.
Don't use double's (or float's) for money or any other calculations, have a look at this article "don't use floats for money". basicly it IEEE 754 giving you all kind of rounding errors.
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.