I'm trying to do some basic math and it keeps popping up as 0. I'm sure it has to do with it being an int but I don't know how to work around it. I need to use integers but the math to arrive at those integers uses decimals. How do I do it?
That's integer division.
To get non-integer results, use doubles instead.
This is not special to blackberry, it's standard java behaviour.
This is because you're doing integer math:
int subexpr1 = 14 / 20; // 0
int subexpr2 = subexpr1 * 100; // 0
Use a double instead or change the order
int expr1 = (int) 14.0/20 * 100; // Very small possibility of rounding errors
int expr2 = 14 * 100 / 20; // Will ignore fraction parts
You can change it to 14*100/20 - and then it will give what you want.
I.e. change the sequence of operations (14/20 is 0)
Your result is being cast as an int, so you are losing precision.
Try
double exp1 = 14/20.0*100;
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
Is there any way to calculate (for example) 50% of 120?
I tried:
int k = (int)(120 / 100)*50;
But it doesn't work.
int k = (int)(120 / 100)*50;
The above does not work because you are performing an
integer division expression (120 / 100) which result is
integer 1, and then multiplying that result to 50, giving
the final result of 50.
If you want to calculate 50% of 120, use:
int k = (int)(120*(50.0f/100.0f));
more generally:
int k = (int)(value*(percentage/100.0f));
int k = (int)(120*50.0/100.0);
Never use floating point primitive types if you want exact numbers and consistent results, instead use BigDecimal.
The problem with your code is that result of (120/100) is 1, since 120/100=1.2 in reality, but as per java, int/int is always an int.
To solve your question for now, cast either value to a float or double and cast result back to int.
I suggest using BigDecimal, rather than float or double. Division by 100 is always exact in BigDecimal, but can cause rounding error in float or double.
That means that, for example, using BigDecimal 50% of x plus 30% of x plus 20% of x will always sum to exactly x.
it is simple as 2 * 2 = 4 :)
int k = (int)(50 * 120) / 100;
Division must be float, not int
(120f * 50 / 100f)
You don't need floating point in this case you can write
int i = 120 * 50 / 100;
or
int i = 120 / 2;
I'm trying to round the users input but I can seem to get my double to round to an int. Basically, when I enter 4.4999 it wont round up to 5.
Any ideas?
Math.ceil() returns the ceiled value. It can't change the value of the variable it takes as argument, because Java passes arguments by value. So you need to do
hours = Math.ceil(hours);
The actual solution is to use double inside the ceil method.
Math.ceil(7 * 50 / 100) will return 3.0 even though the actual value resulting from 7*50/100 is 3.5. It is because since everything is int, the result of 350/100 itself will be 3.
If however, if you give Math.ceil(7 * 50 / 100D), the result would be 4.0.
So, the 4.999 in your question should be a double and not a result of an integer operation like 4999/1000.
Just make sure that whatever you give inside a the ceil is double and not an int.
Both function return the rounded (or ceiled) values, but don't change the variable passed as parameter.
Use eg. hours = Math.ceil(hours);.
Math.ciel returns a Double. Something like this should work (inside of your hours > 0 block):
cost += Math.ceil(hours) * hourlyRate;
You're not assigning the result of Math.ceil(hours) back to hours so it will never round.
int a = 15
int b = 2;
int x = (int) Math.ceil( a / b );
int y = (int) Math.ceil( (double) a / (double) b );
Results:
x: 7
y: 8
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does int exp1 = 14/20*100; equals ‘0’ in java?
I am using this:
int newWidth = Math.round(297 * (40 / 414));
In the code the numbers are actually variables, but those are what they were holding, and when I run the code newWidth comes back as 0, and I was expecting 28 or 29. I don't see what is wrong here...
40 / 414 is rounded to 0 immediately as it only works with integers. You must either cast one of the operands to double/float or use double immediately:
int newWidth = (int)Math.round(297 * (40.0 / 414));
or:
int newWidth = (int)Math.round(297 * ((double)40 / 414));
Because 40/414 equals to 0, so 297*0 = 0 and Math.round(0) = 0
Use doubles instead.
int newWidth = (int)Math.round(297 * (40d / 414));
Change to int newWidth = (int)Math.round(297 * (40.0 / 414));
An int in java uses no decimal places... Therefore you should use a double for this. It is giving you a 0 because inside the () 40/ 414 = 0.
The problem starts with 40/414: that's integer division, which returns an int. In this case: 0.
To fix it, cast one of those ints to a double or float, e.g. ((float) 40 / 414).
The result of 40/414 is zero. This is a consequence of integer division. Change either numerator or denominator to a floating point value to get your desired result
Gonna throw my 2 cents in... as noted, the issue lies in the integer division. Another method for forcing this division to treat the result as a double:
int newWidth = Math.round(297 * (40.0 / 414));
40/414 is rounded to 0.
What you probably want is
int newWidth = (297 * 40) / 414;
Suppose I have a range from 0-100 & I choose a random number X say 29.
Now I increase the range to a big number say a 10-digit 1023654740.
Now I want to find the place of that X in 0-1023654740. (so that is I belive is 29% of 1023654740)
If I perform the calculation using Double, I'm getting an exponent value.
double range = 1023654740;
double position = 29; // Can be any number from 0 - range
Double val = (((double) position / range) * 100);
Result: 2.8329864422842414E-6
But I want final result in int.(dont care if the final value is rounded off or truncated)
Any suggestions
First, your calculation is wrong. According to your description, you probably want to do the following:
Double val = ((double)position / 100) * range;
Then you can get your int value (by truncation) through:
int intVal = val.intValue();
as if your result is Double why you just dont do
val.intValue()
If it is a matter of presenting the result you should have a look at:
String myBeautifulInteger = NumberFormat.getIntegerInstance().format(val);
If it is just a matter of having an integer.
int myInt = val.intValue();
I have the following code in my project:
int percent = 2;
int count = 10;
int percentagefill = (percent/10)*count;
System.out.println(percentagefill);
Basically what is happening is that, I'm setting two variables, percent and count. I then calculate the percentage fill. For some strange reason the percentage fill is resulting in a 0, when in this case it should be 2. Any ideas why? Thanks in advance.
intdivided by int will still result in int. In this case:
(percent/10)*count
= (2/10)*10
= (0) * 10 <-- 0.2 is rounded down to 0
= 0
You can read this question for reference. Also, here's the Java spec where is says that integer division is rounded towards 0. As for the fix, as long as floating point precision does not become an issue, just use double as PaulP.R.O said.
You could divide by 10.0, or change int percent to double percent in order to force a conversion to double. Otherwise, you are getting integer division, which truncates off the decimal part.
Here is a relevant question: "Java Integer Division, How do you produce a double?"
if you really need the result to be an int, you could do the multiply before the divide to avoid the integer division giving you zero.
int percentagefill = (percent*count)/10;
Change this line:
int percentagefill = (percent/10)*count;
To:
double percentagefill = (percent/10.0)*count;
This will use floating point arithmetic (because of the 10.0 instead of 10), and store the result in a double (which has precision past the decimal point unlike an int).
As others have mentioned, you're losing precision with integer division
The solution depends on your needs: if your result needs to be an integer anyway, multiply first:
int percentagefill = (percent*count)/10;
Could be "good enough" for you (you'll get the correct answer rounded down).
If you need to be able to get fractional answers, you need to convert things to floating point types:
double percentagefill = (percent/10.0)*count;
// ^ the .0 makes this a double,
// forcing the division to be a
// floating-point operation.
It's easy to fix:
int percent = 2;
int count = 10;
double percentagefill = (percent/10.0)*count;
System.out.println(percentagefill);
Dave Newton, your answer should have been an answer. :)
The integer 2 / the integer 10 = 0.
The integer 0 * the integer 10 = 0.
You will need a float or double data type. While working with information, always be weary of chances for the interpreter to make data type assumptions and "casts". println takes an intefer and casts to a string for display is one example.
Most of my work is in php and when working with values, 0, NULL, ERROR can all be different things and can yield unexpected results. Sometimes you may need to explicitly cast a variable to a different data type to get the intended results.
This is so due to the fact that you are using the integer data type when you should be using a floating-point data type such as double. This code should result in 2.0:
double percent = 2;
double count = 10;
double percentagefill = (percent/10)*count;
System.out.println(percentagefill);