How to get java to produce decimal points while dividing - java

I'm making a basic calculator where you can plus, times, divide and minus as i was experimenting to see if it worked i noticed that instead of 5 divided by being equal to 1.25 it only displayed 1.
Here's the code i use to handle the math problems:
if (box.getSelectedItem().equals(divide)){
JOptionPane.showMessageDialog(null, Integer.parseInt(first.getText()) / Integer.parseInt(second.getText()), "Answer", -1);
main(args);
}
Is there code that displays the decimal points as well?

Since you are using Integer,it is happening.
Use Double to preserve decimals.
In your case,use
Double.parseDouble(first.getText()) / Double.parseDouble(second.getText())

Integer division will give you Integer. Try using Double or BigDecimal data type.

You need to do the casting
(double)parseInt(first.getText()) / (double)parseInt(second.getText())
Int/Int will give you an Integer. So you need to cast it to Double to get the result in decimal.
EDIT:
If you dont want to show decimal when the result is a whole number then you need to check it like this:
Double res = (double)parseInt(first.getText()) / (double)parseInt(second.getText())
Integer x;
if(res % 1 == 0)
{
x = (int)res
}

Related

Big Error in Java or incongruency with simple operators

I'm beginning in Java, and could anyone explain me why Java gives me these answers?
I have a very simple class trying to learn how to round a number.
I want 2 decimals
so...
public static void main(String[] args) {
double pi1 = Math.PI;
System.out.println("pi1 = " + pi1);
double p2 ;
p2= Math.round(pi1*100)/100;
//p2= Math.round(pi1*100)
//p2=p2/100;
System.out.println("p2 = " + p2);
}
If I run this result is:
p2 = 3.0
Then I change
//p2= Math.round(pi1*100)/100;
p2 = Math.round(pi1*100);
p2 = p2/100;
Now, result is:
p2 = 3.14
as I wanted
Why with these differences? Why the first option doesn't give me 3.14
I think that I've made a correct code with 1st option.
Please, anyone could tell me why?
These things makes me don't trust Java.
Thank you.
I will assume that you know how integer division works in Java. In short, when both sides of / are integral types, like in 314 / 100, the expression evaluates to an integer too, like 3.
Math.round returns a long, which is an integral type. In your first code, you have the expression Math.round(pi1*100)/100. Math.round(...) returns an integer type, 100 is an integer literal, so integer division occurs.
However, in the second code, you first assigned the result of Math.round to p2. The long returned is implicitly converted to a double first, and stored in p2. You then wrote an expression in p2: p2/100. Here, one of the operands is double, so integer division does not occur.
Therefore, the one liner version that is the same as the second code is:
p2 = ((double)Math.round(pi1*100))/100;
You don't see the double conversion in the second code because it is done implicitly.
A note on rounding
This way rounding doubles should be used if you want to do calculations with the rounded number afterwards. If you just want to display a rounded number as output, you should use String.format, System.out.printf, or DecimalFormat. Read more about these methods here.
No mistake here, it works properly. Method Math.round(double) returns type long.
In your first variant, you receive result long 314 and divide it by 100 and get the result 3, and then assign it back to double.
In your second variant, you receive long result 314 and assign it back to double. Dividing double keeps precision as opposed to dividing long, so you get the correct result of 3.14
There for make p2= Math.round(pi1*100)/100; as
p2= Math.round(pi1*100) / 100.0;
Output -:
pi1 = 3.141592653589793
p2 = 3.14

Get the hundredths place value digit in a double variable using java

I am trying to get the digit in the hundredth's place of a double value (second digit after the decimal).
So, for example, if the double value is 48.4569999, I want to get the value 5 using any Math or BigDecimal methods, which is the hundredth's place after decimal.
I have tried the following code:
BigDecimal src = new BigDecimal("48.4569999");
BigDecimal a = src.remainder(BigDecimal.ONE);
System.out.println("a : " + a);
which results in .456999 but I dont want to use any String functions to get to the second digit. Is there any Math or Bigdecimal function to do this please ? Your help is appreciated.
Why not multiply by 100, to push your desired value to the right place, cast to int (to remove anything < 1) and then do % 10, which will give you the remainder (which will be your desired digit).
You may be looking for movePointRight(int).
int a = src.movePointRight(2).remainder(BigDecimal.TEN).intValue();
prints
a : 5

different result in java how can it be rectified

Simple calculation gives different result in java.
int a=5363/12*5;
out.println(a);// result is 2230
But actually result should be 2234.5
How can this java result be rectified?
Two issues:
The expression 5363/12*5 gives an integer result (in particular, the division is integer).
The variable a is of type int (integer).
To fix:
double a=5363.0/12*5;
out.println(a);
Note that in general you can't expect to get exact results when using floating-point arithmetic. The following is a very good read: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
5363, 12, and 5 are all being interpreted as ints. the calculation actually being performed here is:
5363/12 = 446.9… - truncated to the int value 446
446 * 5 = 2230
Try specifying a as a float, and indicate that the numbers in the calculation are also created as floats:
float a = 5363f/12f*5f
Take a as double.
Taking a as int will round it to the integer.
Because your all the literal numbers in the right hand side are integers (e.g. 5363 as opposed to 5363.0) expression is being calculated using integer arithmetic semantics i.e. / does whole number division. Thus 5262/12 equals 446 and 446*5 equals 2230. Also your variable a is an int which can only ever hold an integer value.
To fix this you need to do two things. Change the type of a to a decimal type e.g. float or double b) have at least one of 5363 and 12 represented as a decimal type e.g.
double a= 5363.0/12.0*5
Instead of using double you can re-order your expression.
Assuming 5363/12*5 = 5363*5/12 this will give you a closer answer. You have commented you want to round the result so instead you have to add half the value you are dividing by.
int a = (5363 * 5 + /* for rounding */ 6) / 12;
System.out.println(a);
prints
2235
An int is an Integer - nothing after the ..
You should be using
double a = 5363d/12*5;
It seems it has some int/double rounding issue:
double a=((double)5363/12)*5;
System.out.println("VALUE: "+a);
Prints:
VALUE: 2234.5833333333335
Edit: rounding the result to an integer value:
double a=((double)5363/12)*5;
long b=Math.round(a); //you can cast it to an int type if needed
System.out.println("ROUNDED: "+b);
Prints:
ROUNDED: 2235
Use double
double a = 5363/12*5;
System.out.println(a);
or
cast the integer, to prevent loss or precision.
int a = ((int) 5363/12*5);
System.out.println(a);

Beginners Java Question (int, float)

int cinema,dvd,pc,total;
double fractionCinema, fractionOther;
fractionCinema=(cinema/total)*100; //percent cinema
So when I run code to display fractionCinema, it just gives me zeros. If I change all the ints to doubles, then it gives me what Im looking for. However, I use cinema, pc, and total elsewhere and they have to be displayed as ints, not decimals. What do I do?
When you divide two ints (eg, 2 / 3), Java performs an integer division, and truncates the decimal portion.
Therefore, 2 / 3 == 0.
You need to force Java to perform a double division by casting either operand to a double.
For example:
fractionCinema = (cinema / (double)total) * 100;
Try this instead:
int cinema, total;
int fractionCinema;
fractionCinema = cinema*100 / total; //percent cinema
For example, if cinema/(double)total is 0.5, then fractionCinema would be 50. And no floating-point operations are required; all of the math is done using integer arithmetic.
Addendum
As pointed out by #user949300, the code above rounds down to the nearest integer. To round the result "properly", use this:
fractionCinema = (cinema*100 + 50) / total; //percent cinema
When you divide two ints, Java will do integer division, and the fractional part will be truncated.
You can either explicitly cast one of the arguments to a double via cinema/(double) total or implicitly using an operation such as cinema*1.0/total
As some people have already stated, Java will automatically cut off any fractional parts when doing division of integers. Just change the variables from int to double.

Java using Mod floats

I am working on an exercise in Java. I am supposed to use / and % to extract digits from a number. The number would be something like 1349.9431. The output would be something like:
1349.9431
1349.943
1349.94
1349.9
I know this is a strange way to do but the lab exercise requires it.
Let's think about what you know. Let say you have the number 12345. What's the result of dividing 12345 by 10? What's the result of taking 12345 mod 10?
Now think about 0.12345. What's the result of multiplying that by 10? What's the result of that mod 10?
The key is in those answers.
if x is your number you should be able to do something like x - x%0.1 to get the 1349.9, then x - x%.0.01 to get 1349.94 and so on. I'm not sure though, doing mod on floats is kind of unusual to begin with, but I think it should work that way.
x - x%10 would definetly get you 1340 and x - x%100 = 1300 for sure.
Well the work will be done in background anyway, so why even bother, just print it.
float dv = 1349.9431f;
System.out.printf("%8.3f %8.2f %8.1f", dv, dv, dv);
Alternatively this could be archived with:
float dv = 1349.9431f;
System.out.println(String.format("%8.3f %8.2f %8.1f", dv, dv, dv));
This is a homework question so doing something the way you would actually do in the real world (i.e. using the format method of String as Margus did) isn't allowed. I can see three constraints on any answer given what is contained in your question (if these aren't actually constraints you need to reword your question!)
Must accept a float as an input (and, if possible, use floats exclusively)
Must use the remainder (%) and division (/) operator
Input float must be able to have four digits before and after the decimal point and still give the correct answer.
Constraint 1. is a total pain because you're going to hit your head on floating point precision quite easily if you have to use a number with four digits before and after the decimal point.
float inputNumber = 1234.5678f;
System.out.println(inputNumber % 0.1);
prints "0.06774902343743147"
casting the input float to a double casuses more headaches:
float one = 1234.5678f;
double two = (double) one;
prints "1234.5677490234375" (note: rounding off the answer will get you 1234.5677, which != 1234.5678)
To be honest, this had me really stumped, I spent way too much time trying to figure out how to get around the precision issue. I couldn't find a way to make this program work for 1234.5678f, but it does work for the asker's value of 1349.9431f.
float input = 1349.9431f;
float inputCopy = input;
int numberOfDecimalPoints = 0;
while(inputCopy != (int) inputCopy)
{
inputCopy = inputCopy * 10;
numberOfDecimalPoints++;
}
double inputDouble = (double) input;
double test = inputDouble * Math.pow(10, numberOfDecimalPoints);
long inputLong = Math.round(test);
System.out.println(input);
for(int divisor = 10; divisor < Math.pow(10, numberOfDecimalPoints); divisor = divisor * 10)
{
long printMe = inputLong - (inputLong % divisor);
System.out.println(printMe / Math.pow(10, numberOfDecimalPoints));
}
Of my three constraints, I've satisfied 1 (kind of), 2 but not 3 as it is highly value-dependent.
I'm very interested to see what other SO people can come up with. If the asker has parsed the instructions correctly, it's a very poor exercise, IMO.

Categories