This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
I am dividing two int values, and im expecting to get a double one. but it works very strange, it has the correct values just before division but it doesnt give the right answer.
public void Analyse() {
for (FlowPacket fp : this.flow.GetAll()) {
if (fp.direction==1){
this.sentPackets++;
this.sentLength = this.sentLength + fp.packetLength;
}
else{
this.receivedPackets++;
this.receivedLength = this.receivedLength + fp.packetLength;
}
}
if(this.receivedPackets==0)
this.receivedPackets = 1;
}
public double CalcRatio() {
return (this.sentPackets/this.receivedPackets);
}
----------------------------main--------------------------------
System.out.print("Sent packets: " + analyser.getTotalSentPackets() + " , ");
System.out.print("Received packets: " + analyser.getTotalReceivedPackets() + " , ");
System.out.print("ratio: " + analyser.CalcRatio() + " , ");
----------------------------outout------------------------------
Sent packets: 2694 , Received packets: 5753 , ratio: 0
(double)this.sentPackets/this.receivedPackets
... should fix it.
The result of the division is cast to a double AFTER integer division (with rounding down) is performed. Cast one of the integers to a double BEFORE dividing so that double division occurs.
When dividing an int by an int the answer will be an int. Therefor it will cut off any remainder there may be in the answer.
In order to get a double answer you must cast one of the ints to a double.
Cast at least one of the ints to (double) before dividing.
Need to cast to double...
public double CalcRatio() {
return ( (double) this.sentPackets/ (double) this.receivedPackets);
}
It is not only Java-specific behaviour. It works the same way in .NET, too.
Related
This question already has answers here:
Why is Java's division broken?
(6 answers)
Closed 4 years ago.
I was having some problem when trying to convert bytes to megabyte in Java. What I have tried to do is:
long inodeSpace = 100000;
long MEGABYTE = 1024L * 1024L;
long inodeSpaceInMb = inodeSpace / MEGABYTE;
System.out.println("INODE SPACE " + inodeSpace);
System.out.println("INODE MB " + inodeSpaceInMb);
I tried to print out the inodeSpaceMb, however, I am getting 0. Any ideas why is it so?
Cast one of the two into a double and store the result in a double. Like:
double inodeSpaceInMb = (double) inodeSpace / MEGABYTE;
If you also want some precision to a specific decimal place when you do the conversion then you can do this:
public double bytesToMegabytes(long byteValue, int precision) {
if (precision < 0) {
throw new IllegalArgumentException("Precision can not be less than 0!");
}
double mbValue = byteValue * 0.000001;
BigDecimal bigDec = new BigDecimal(mbValue);
bigDec = bigDec.setScale(precision, RoundingMode.HALF_UP);
return bigDec.doubleValue();
}
This question already has answers here:
percentage of two int?
(4 answers)
Closed 5 years ago.
I have such code:
int number1 = 20;
int number2 = number1/100;
I want to get percentage of number1 as 0,2 -> I suppose int should be converted into some other type. But I need 0,2 to use for BigDecimal number. How can I get this 0,2 from int number1 = 20?
int number1 = 20 has to be in that type.
Will be grateful for help.
Using a BigDecimal is appropriate here. You can use BigDecimal.valueOf in order to convert int to BigDecimal. Then, you can divide by specifying a scale and a rounding mode.
Example :
System.out.println(
BigDecimal.valueOf(20).divide(BigDecimal.valueOf(100), 1, RoundingMode.HALF_UP)
);
Will display :
0.2
With a different scale :
System.out.println(
BigDecimal.valueOf(20).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP)
);
It will display :
0.20
Or like stated in the question comments, you can also create directly the BigDecimal from a String :
System.out.println(new BigDecimal("0.2"));
Divide the int by a floatvalue to give to it a floating number representation and assign it to a floating number.
float number2 = number1/100F;
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 5 years ago.
I have the number "159.82" and I need to get it to print just "82"
What I have been trying is something along the lines of
double total = 159.82;
System.out.println(total - (int) total);
But that leaves me with 0.8199999999999 so clearly I am doing something wrong.
Simple way: Turn it into an String, use indexOf to find the ".", use substring to print 82.
Would this fit what you're looking for? It outputs the decimal value, rounded to two places, as a String.
double total = 159.82;
String decimalValue = String.format("%.2f", total).split("\\.")[1];
System.out.println(decimalValue);
(Prints "82")
Due to how float/double works, the easiest solution could be to work with strings. This will return the decimals of any double input.
double input = 159.82;
String decimals = Double.toString(input);
decimals = decimals.substring(decimals.lastIndexOf('.') + 1);
System.out.println(decimals);
// prints "82"
final int fraction = Integer.valueOf((total+"").replaceFirst("-?\\d+\\.", ""));
System.out.println( fraction );
Another solution with replaceAll, so you can replace everything until the dot :
double total = 159.82;
System.out.println(String.valueOf(total).replaceAll("^.*\\.", ""));// output = 82
This can work either with negative numbers for example :
double total = -159.82; // output = 82
Another solution if you want to get only 2 numbers then you can use :
double total = 159.82; // positive or negative
int result = Math.abs((int) (total * 100) % 100);
System.out.println(result); // output = 82
This question already has answers here:
Why does the division of two integers return 0.0 in Java? [duplicate]
(6 answers)
Closed 8 years ago.
So this is a portion of the code I'm using, we were only supposed to begin by fixing some logical errors because of wrong answers. I found a couple of syntax errors as well that wouldn't let the compiler finish up...I keep getting "0" for fToC...
//declaration statements
final int BOILING_IN_F = 212;
int fToC;
string output;
//there is other code between that has nothing
//to do with outputting the boiling point.
fToC = (5/9) * (BOILING_IN_F - 32);
output = BOILING_IN_F + " in Fahrenheit is " + fToC
+ " in Celsius.";
System.out.println(output); //this is outputting 0 for fToC
System.out.println();
Answers were useful, except I needed to declare fToC as a double before compiling and running the program. Thank you.
You are performing Java's integer division with 5/9, which must result in another integer -- 0, so the result is 0. Use double literals to force floating-point math.
fToC = (5.0/9.0) * (BOILING_IN_F - 32);
You'll need fToC to be a double (and change the typo string output to be String output).
(5/9) is 0 due to int division. Try (5.0/9)
The full expression should be :
fToC = (5.0/9) * (BOILING_IN_F - 32);
(5/9) You're diving two integers, so this is truncated, so it equals 0. And you're multiplying that 0 with another number.
Use instead (5.0f/9.0f) to precise the fact that your number are actually decimal numbers.
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 8 years ago.
Hey guys I'm a new Java learner. I have a problem with this code:
I dont see why it prints only the value of a, and not of ((9/5)*a+32)
for example if a = 50 , ((9/5)*a+32) = 82 but when I compile this it prints a=50 and ((9/5)*a+32)=82.
Scanner tt = new Scanner(System.in);
a = tt.nextInt();
System.out.println(a + " degrees °C match " + ((9/5)*a+32) + "°F");
Can someone explain this to me?!
9/5 is being done using integer maths. In integer, 9/5 is 1.
Try:
(9*a)/5+32
or:
(int)((9.0/5)*a+32)
try using
1.80 * a + 32
or
9 / 5.0 * a + 32
what happens in your code is that you are dividing an integer by integer and
integer / integer = integer
it leads to precision loss..so you have to convert it to float or double type.
You are performing integer division, I believe you wanted
System.out.println(a + " degrees °C match "
+ ((((double) 9) / 5) * a + 32) + "°F");