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();
Related
I am little bit lost with double decimal point at the moment.
I have basically two methods, which will set the values for double amount and double receive. Then another integer variable where I would like to set the (receive - amount) * 100.
For example if I have two double values and I want to set their difference to an int value, then would it be possible?
My problem is that if I try to find the difference between two values, then e.g. (10.0- 9.40), then it will be 0.599999999. How can I get 0.60 out of it inside the method and use it? I know how to use NumberFormat or DecimalFormat. Should I use one inside the method to set the number of decimal points?
you can round off the value im using a decimalformat to round off the number. You can pass a double variable inside the method and this will return a number rounded off to 2 decimal points.
double RoundTo2Decimals(double val) {
DecimalFormat df2 = new DecimalFormat("###.##");
return Double.valueOf(df2.format(val));
}
You can use BigDecimal to perform the rounding, or you can use maths like this. It basically multiplies by 100, rounds and divides by 100.
/**
* Performs a round which is accurate to within 1 ulp. i.e. for values very close to 0.5 it
* might be rounded up or down. This is a pragmatic choice for performance reasons as it is
* assumed you are not working on the edge of the precision of double.
*
* #param d value to round
* #return rounded value
*/
public static double round2(double d) {
final double factor = 1e2;
return d > WHOLE_NUMBER / factor || d < -WHOLE_NUMBER / factor ? d :
(long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor;
}
Easiest solution could be below. Modifications and improvements are welcomed.
double x =10.0;
double y =9.40;
int xy =0;
DecimalFormat df = new DecimalFormat("#.##");
xy = (int) (Double.valueOf(df.format(x-y))*100);
System.out.println(xy);
I think I figured it out by using Math.round().
I will just ask whether my solution is a good or a bad idea to use? I am not just so familiar with BigDecimal. Long story short about the code. Example inputs are as: a = 9.40 and b = 10.0
private int difference;
private double amountDue;
private double receive;
public void setAmount(double a) {
amountDue = a;
}
public void receive(double b) {
receive = b;
difference = (int)Math.round(100 * (receive - amount));
I just needed to get int difference as 0.60 * 100 = 60, but as I mentioned before then just calculating the difference caused 0.59999999.
Just an extra question. Is it ok for me to initialize int balance variable inside one method as I have done?
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
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;
I have the following code:
float fl = ((float)20701682/(float)20991474);
And that gives me fl = 0.9861948.
I would like to convert 0.9861948 to 2% since 2% has been downloaded.
I'm downloading a file and calculating progress.
Any help would be grate.
you have constant values in the code, you should replace them with the variables representing the amount downloaded and the total size:
float downloaded = 50;
float total = 200;
float percent = (100 * downloaded) / total;
System.out.println(String.format("%.0f%%",percent));
output:
25%
I guess you mean something like
int percentage = (1 - fl) * 100;
to calculate the percentage.
But for fl = 0.9861948 this gives 1 (1.38052 casted to int).
If you want 2 instead, you could use Math.ceil:
int percentage = (int) Math.ceil((1 - fl) * 100); // gives 2
I wrote two methods below to convert a float number to a string displayed as percentage:
//without decimal digits
public static String toPercentage(float n){
return String.format("%.0f",n*100)+"%";
}
//accept a param to determine the numbers of decimal digits
public static String toPercentage(float n, int digits){
return String.format("%."+digits+"f",n*100)+"%";
}
Test Case1:
public static void main(String[] args) {
float f = 1-0.9861948f;//your number,0.013805211
System.out.println("f="+f);//f=0.013805211
System.out.println(toPercentage(f));//1%
System.out.println(toPercentage(f,2));//1.38%
}
Test Case2:
If you want 2% instead, try to input a param like this:
float f = 1-0.9861948f;//your number,0.013805211
f= (float)(Math.ceil(f*100)/100);//f=0.02
System.out.println("f="+f);f=0.02
System.out.println(toPercentage(f));//2%
System.out.println(toPercentage(f,2));//2.00%
When you output the float just tell the string conversion to only allow no/one/whatever trailing digits:
System.out.printf("We have downloaded: %.0f %%%n", (1-fl) * 100);
But I'm not sure why exactly you'd want to round 1.4% to 2%.. if you really want that it gets a lot more complicated for really no good reason.
How about (1.0 -fl ) * 100 ?
Convert this to an integer and you wouldn't have any issues.
Since percent means "per 100," perhaps you could multiple fl by 100. Since, for some reason, you want .98 to mean 2%, you would then subtract the result from 100.
You need something like:
float allSize = ...;
float downloaded = ...;
int percent = (allSize - downloaded/100 * 100.0)/allSize
(downloaded/100 * 100.0) - used for make two digit of fractional part;
After applying the ((1-fl)*100) logic you can use DecimalFormat or String.format().
float fl = ((float)20701682 / (float)20991474)*100;
int pct = 100 - Math.floor(fl)
i have an Integer value:
Integer value = 56472201;
Where the value could be positive or negative.
When I divide the value by 1000000, I want this result in the form 56.472201 but instead it gives me just the quotient. How am I able to get both the quotient and remainder values?
cast it to float and then do it:
int i = 56472201;
float j = ((float) i)/1000000.0
Edit: Due to precision(needed in your case), use double. Also as pointed by Konrad Rudolph, no need for explicit casting:
double j = i / 1000000.0;
You have to convert the value to a floating point type first, otherwise you will be doing an integer division.
Example in C#:
int value = 56472201;
double decimalValue = (double)value / 1000000.0;
(The cast is actually not needed in this code, as dividing by a floating point number will cast the value to match, but it's clearer to write out the cast in the code as that is what actually happens.)
If you divide an int by a double you will be left with a double result as illustrated by this unit test.
#Test
public void testIntToDouble() throws Exception {
final int x = 56472201;
Assert.assertEquals(56.472201, x / 1e6d);
}
1e6d is 1 * 10^6 represented as a double