This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 3 years ago.
I have two int numbers a, b always >= 0. I want to divide a by b and return the rounded up percentage to the nearest integer.
Example: 18/38 should return 47 and 13/38 should return 34.
How can I accomplish this?
I tried the following but it didn't work
c = Math.round(a/b) * 100;
Since a and b are integers, a/b will use integer division, and only return the "whole" part of the result. Instead, you should multiply a by 100.0 (note the .0, which makes it a double literal!) to use floating-point division, and then ceil the result, and truncate it to an int:
c = (int) Math.ceil(100.0 * a / b);
public static void main(String[] args){
int a=18,b=38,c=0;
c = (int) Math.round(100.0 * a / b);
System.out.println(c);
}
As #Mureinik said that a and b are integers,they will use integer division.
you should multiply 100 by a like above. and keep using .round instead of .ceil inorder to get 47 as output which is intended .ceil will give you 48 as output.
c = (int) Math.round(100.0 * a / b);
This should give desired result.
You need to do follow things to get the result
Double res= Double.valueof(a/b);
DecimalFormat decimalFormat = new DecimalFormat("#.00");
String num= decimalFormat.format(res);
Int finalResult = Integer.valueof(num)*100;
Thanks
Related
I need to cast a double to an int in Java, but the numerical value must always round down. i.e. 99.99999999 -> 99
Casting to an int implicitly drops any decimal. No need to call Math.floor() (assuming positive numbers)
Simply typecast with (int), e.g.:
System.out.println((int)(99.9999)); // Prints 99
This being said, it does have a different behavior from Math.floor which rounds towards negative infinity (#Chris Wong)
To cast a double to an int and have it be rounded to the nearest integer (i.e. unlike the typical (int)(1.8) and (int)(1.2), which will both "round down" towards 0 and return 1), simply add 0.5 to the double that you will typecast to an int.
For example, if we have
double a = 1.2;
double b = 1.8;
Then the following typecasting expressions for x and y and will return the rounded-down values (x = 1 and y = 1):
int x = (int)(a); // This equals (int)(1.2) --> 1
int y = (int)(b); // This equals (int)(1.8) --> 1
But by adding 0.5 to each, we will obtain the rounded-to-closest-integer result that we may desire in some cases (x = 1 and y = 2):
int x = (int)(a + 0.5); // This equals (int)(1.8) --> 1
int y = (int)(b + 0.5); // This equals (int)(2.3) --> 2
As a small note, this method also allows you to control the threshold at which the double is rounded up or down upon (int) typecasting.
(int)(a + 0.8);
to typecast. This will only round up to (int)a + 1 whenever the decimal values are greater than or equal to 0.2. That is, by adding 0.8 to the double immediately before typecasting, 10.15 and 10.03 will be rounded down to 10 upon (int) typecasting, but 10.23 and 10.7 will be rounded up to 11.
(int)99.99999
It will be 99.
Casting a double to an int does not round, it'll discard the fraction part.
Math.floor(n)
where n is a double. This'll actually return a double, it seems, so make sure that you typecast it after.
This works fine int i = (int) dbl;
new Double(99.9999).intValue()
try with this, This is simple
double x= 20.22889909008;
int a = (int) x;
this will return a=20
or try with this:-
Double x = 20.22889909008;
Integer a = x.intValue();
this will return a=20
or try with this:-
double x= 20.22889909008;
System.out.println("===="+(int)x);
this will return ===20
may be these code will help you.
Try using Math.floor.
In this question:
1.Casting double to integer is very easy task.
2.But it's not rounding double value to the nearest decimal. Therefore casting can be done like this:
double d=99.99999999;
int i=(int)d;
System.out.println(i);
and it will print 99, but rounding hasn't been done.
Thus for rounding we can use,
double d=99.99999999;
System.out.println( Math.round(d));
This will print the output of 100.
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 6 years ago.
The question require me to write a Java program to show the results of the following cast operator expressions:
(double) (23 / 14) + 7.65
My Code:
public class op {
public static void main(String [] args) {
int num = 23/14;
double r1 = (double) num;
double result = r1 + 7.65;
System.out.println("Results: "+ result);
}
}
I don't think I have done correctly, what are the problems of my code?
By the way, can someone tell me what are the differences between long, double, int, float? How do we know when to use these primitive data types? I read an explanation here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
but is there any 'human-version' of the explanation?
Thank you for your help.
The problem is due to the used types.
Since you divide two integers (23 and 14), the result is considered and int as well. Therefor, 23/14 = 1.642857142857143, which is truncated to fit in an int result, more specifically, 1.
result is the sum of 1 (int) and 7.65 (double). Since one of them is a double, to other is converted to the "upper" type as well (double) and the operation becomes 1.0+7.65 = 8.65.
The result is correct, because you asked the result of (double) (23 / 14) + 7.65 which means the result of casting the result of the operations in brackets to double summed with 7.65. Which is 8.65 as previously explained.
If you want to use a division using doubles, consider:
double r1 = 1.0 * 23/14;
Lets see step-by-step:
int num = 23/14; // int division of 23/14 results in 1
So, here num = 1
When you cast num to double value of r1 is setted to 1.0.
double result = r1 + 7.65; //1.0 + 7.65 = 8.65
ok, int is short term for INTEGER which are natural numbers that we use normally but with no decimal places and if your number has some value in between roughly -2 billion to +2 billion. if your range exceeds that and you still want an integer then go for long data type.
floats are for decimal values like 3.147 with a range of +10*38 to -10*38 or so, but if your range exceeds this(practically this happens rarely) go for double.
coming to the code you put here , if you divide a int by another int (like 23/14) you get only get the integer part of the answer(only '1' in 23/14=1.642...) , next when you cast it to double you get 1.0 and next you are going to add that to 7.65 which will make the ultimate answer as 8.65 hope this answers your Q....
You could change this int num = 23/14
to double num = ((double) 23)/14
or double num = (23 * 1.0)/14
This question already has answers here:
fixed point arithmetics in java with fast performance
(4 answers)
Closed 7 years ago.
I have two double variables:
double a = 1.109
double b = 5.0E-5;
But b is changable and I want to achieve fixed numbers of decimal places depending of b number, for example above I want achieve this result:
Result = 1.10900
But not only print, I need to send it to other method and my double must have fixed numbers of decimal places like in example.
It sounds like you want arbitrary precision on the actual value (as opposed to just output). double doesn't give you that. BigDecimal does though. Its BigDecimal(String) constructor sets the value and the scale (number of places to the right of the decimal) from a string, so:
BigDecimal d = new BigDecimal("1.10900");
BigDecimal then gives you various math operations to stay within that scale, with various rounding options.
If at some point you need to get the double value of the BigDecimal, you can use its doubleValue method. But note that at that point, again, you don't have a fixed number of places to the right of the decimal anymore.
Here's an example contrasting BigDecimal and double (Live Copy):
import java.math.*;
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
BigDecimal bd = new BigDecimal("1.10900");
bd = bd.divide(new BigDecimal("27"), BigDecimal.ROUND_HALF_DOWN);
System.out.println("1.109 / 27 using BigDecimal to five places: " + bd);
double d = 1.109;
d = d / 27.0;
System.out.println("1.109 / 27 using double: " + d);
}
}
Output:
1.109 / 27 using BigDecimal to five places: 0.04107
1.109 / 27 using double: 0.041074074074074075
Try using a number formatter:
NumberFormat formatter = new DecimalFormat("#0.00000");
double a = 1.109;
double b = 5.0E-5;
System.out.println(a);
System.out.println(b);
Output:
1.10900
0.00005
A simple solution is to round the result as needed. This is not only faster than using BigDecimal it can be less error prone as Java doesn't have language support for BigDecimal making it harder to write/read and validate. A simple method for rounding half up for 5 decimal spaces is
public static double round5(double d) {
final double factor = 1e5;
return d > Long.MAX_VALUE / factor || d < -Long.MAX_VALUE / factor ? d :
(long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor;
}
Note: when you print the double you will still need to specify the number of decimal places you need e.g.
System.out.printf("%.5f", value);
Use java printf-like routine (note it produces platform dependent decimal separators):
String.format("%.5f", a)
This question already has answers here:
How to multiply a BigDecimal by an integer in Java
(3 answers)
Closed 8 years ago.
I have one value like 0.0004 when I store this in Integer it is converting into Exponential format, So I have used Bigdecimal to convert it to normal value like below
Bigdecimal x=BigDecimal.valueOf(0.0004)
Now I am trying to multiply as x*100 but I am getting below error.
Error: The operator * is undefined for the argument type(s) BigDecimal, int
Because of this error if I use this without bigdecimal again it is converting to EXponential.
Can any one please suggest me the way to multiply Bigdecimal and int.
googled a lot but couldn't find the correct solution.
Thanks for your time
You can use BigDecimal.multiply to multiply your BigDecimal.
However, the int value of 0.0004 * 100 will be 0, which is probably not what you want.
Finally, you can alter the how the BigDecimal is represented in terms of fractional digits by using a NumberFormat instance and formatting your Number.
Here's an example:
BigDecimal x= BigDecimal.valueOf(0.0004);
BigDecimal y = x.multiply(new BigDecimal("100"));
int z = y.intValue();
System.out.printf("y is %s\tz is %d%n", y, z);
// edit to truncate fractional digits
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
System.out.printf("y (2 fraction digits) is %s", nf.format(y));
Output
y is 0.04000 z is 0
y (2 fraction digits) is 0.04
BigDecimal's are objects. They don't have normal operators.
Instead of a normal multiplication operator like x*10, you need to call the method multiply in BigDecimal:
x = x.multiply(new BigDecimal(10));
If you want to store it in a new value:
BigDecimal n = x.multiply(new BigDecimal(10));
And to convert that to a primative:
double d = n.doubleValue();
int i = n.intValue();
However, if you're trying to use decimals, why not just use a double:
double x = 0.0004;
double n = x*100;
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Dividing two integers in Java gives me 0 or 100?
(5 answers)
Closed 9 years ago.
OK so this is a problem in a larger piece of code which does'nt seem to make sense. below is the code which is the problem... It prints Ratio = 0.0 the console when launched it should be equal to ~0,348.
public class MathTest {
public static void main(String[] args) {
double ratio = 29511 / 84812;
System.out.println("Ratio = "+ ratio);
}
}
Edit:
What if the code is this:
public class MathTest {
public static void main(String[] args) {
int int1 = 7;
int int2 = 13;
double double1 = int1/int2;
System.out.println("double1 = "+ double1);
}
}
It again prints "0.0".
You have unwittingly used integer division when you say 29511 / 84812, which in Java, loses the decimal points. Use double literals (with .0 added) instead:
double ratio = 29511.0 / 84812.0;
Other solutions that work here:
Cast one of them to a double: (double) 29511 / 84812
Use 'D' as another way to indicate a Java double literal: 29511D / 84812D
You are doing integer division because 29511 and 84812 are ints. The result of the division is 0, and you are saving it as a double so it becomes 0.0.
To fix this, cast one of the operands on the right side of the assignment to a double.
double ratio = (double)29511 / 84812;
Replace double ratio = 29511 / 84812 with double ratio = 29511.0 / 84812.0;
It make perfect sense. You are dividing two integers to get an integer. This means 0 in this case.