This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does (360 / 24) / 60 = 0 … in Java
Having problems with floats and longs in Java
float f = 0.100f;
f = 3/180;
At the minute i am trying to do something like this with object and their attributes, but even to this simplest form my program returns 0.0.
I have tried this with Longs as well as still the same result. It's been a long day and maybe it's something simple but I'm at a brick wall.
Your expression 3/180 is performing an integer division, and it is then casting that into the float f. In integer division, 3/180 will return 0, and this is what you are seeing.
What you probably want to do is just add a decimal point to your numbers: f = 3.0/180.0;
3/180 is integer division.
Therefore, the result is truncated to an integer.
You need to perform floating-point division: 3/180f
You do an integer division. So you get an int which is casted back to a float. Try this:
f = 3/180.0;
or
f = 3/180f;
Try 3.0/180. Otherwise, you are dividing two integers and you run into integer truncation. When you do integer division the result is also an integer, not a floating point number.
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));
This question already has answers here:
How can I divide properly using BigDecimal
(2 answers)
Closed 5 years ago.
The title says it all: How do I divide a BigInteger by a floating point number in Java? I don’t need the fraction part of the division, it is okay to have it either rounded or truncated (however I would be interested which one applies).
The “obvious” does not even compile:
BigInteger x = BigInteger.valueOf(73).pow(42);
BigInteger y = x.divide(Math.PI); // The method divide(BigInteger) in the type BigInteger is
// not applicable for the arguments (double)
System.out.println(y);
I expected this one to work:
BigInteger y = new BigDecimal(x).divide(BigDecimal.valueOf(Math.PI)).toBigInteger();
Unluckily, it gives an ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. This is true for π, of course…
Of course, this one works, but it is way too slow…
BigInteger y = BigInteger.valueOf(-1);
BigDecimal σ = BigDecimal.ZERO;
while(σ.compareTo(new BigDecimal(x)) < 0) {
y = y.add(BigInteger.ONE);
σ = σ.add(BigDecimal.valueOf(Math.PI));
}
What’s the correct, canonical way?
You have to add RoundingMode to divide function, otherwise java doesn't know how to round the division and gives you ArithmeticException
BigInteger y = new BigDecimal(y).divide(BigDecimal.valueOf(Math.PI), RoundingMode.HALF_UP).toBigInteger();
All Rounding types are well explained in the documentation link above.
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 7 years ago.
double x = 0.00090;
double b = 0.00100;
double c = x - b;
produces
-1.0000000000000005E-4
instead of
-0.0001
and
double x = -0.09;
double b = 0.001;
double c = x * b;
produces
-8.999999999999999E-5
instead of
-0.00009
I also tried with
Math.round(c) and Math.round(c*100.0)/100.0
but it is producing same results or results with incomplete number range after decimal.
That's how numeric operations are defined in the specification.
Decimal numbers are internally represented as the closest approximation, which in some cases is not the exact literal value.
If you need precise numeric computation, you have to use BigDecimal.
The answers are correct. You might want to read up on how doubles are stored in binary digits. its because it's base 2. If we used something like base 3, then in normal digits, 2/3 would be 0.66666666... but in the "tridigit" it would be 0.2
The E notation is confusing you (explanation on how it works here)
-1.0000000000000005E-4
is
-0.00010000000000000005
in standard notation and
-8.999999999999999E-5
is
-0.00008999999999999999
in standard notation. All the answer you see are correct (almost, but they are very close, decimal math isn't always precise), just using the E notation.
try this:
double x = 0.00090;
double b = 0.00100;
BigDecimal xd = new BigDecimal(x).setScale(10, RoundingMode.HALF_UP);
BigDecimal bd = new BigDecimal(b).setScale(10, RoundingMode.HALF_UP);
BigDecimal cd = xd.multiply(bd);
double c = cd.doubleValue();
System.out.println(c);
For precise calculations, like money calculations, you should use BigDecimals, because they have desired precision, and don't lost any accuracy.
If you prefer printing without "E", try this line:
System.out.println(cd.toPlainString());
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
Here's the code:
class testsum
{
public static void main(String arg[])
{
double sum=0;
double fraction;
fraction=-1/9;
System.out.println("fraction: "+fraction);
fraction=-1;
fraction=fraction/9;
System.out.println("fraction: "+fraction);
}
}
the outputs are 0 and then -0.11111111
why was the first output 0 and not -0.11111111111?
It's doing integer division in the first example as this is the default type for a numeric literal. Try changing it to -1.0/9 (or 1d/9d - the d suffix indicates a double) and you should get the same answer.
1 and 9 are both integer. Try
1.0/9
This is why it works for fraction/9, since fraction is a double.
When you do -1/9, it says "-1, that's an int. 9, that's an int. -1 / 9 in integer division is 0. Oh, now I need to cast to double."
Changing it to -1.0 / 9 should solve the problem.
Try wrapping the "-1/9" in brackets.
The first one is 0 because it is doing integer division. -1 and 9 and integers and when divided equal 0. The result is then converted into a double so it can be stored in fraction. The easiest solution is this:
fraction = -1.0/9;
Because -1 and 9 are integers, so -1/9 is an integer division (with the result 0, which when cast to double is 0.0).
To do a floating point division, you should convert one of the numbers to double, (double) 9, 9d or simply 9.0.
In the latter case, fraction is already double (-1.0) so fraction/9 is a floating point division.