Related
I am dividing two ints x/y,. Say 3/2. Then one would get 1 as result though the actual result is 1.5. Ok this is obvious as it's int division. But I want 1.5 to be rounded off to the next highest int not the immediate lowest. So 2 is desired as result. (One can write simple logic using mod and then division... But am looking for simple Java based API). Any thoughts?
You can, in general, write (x + y - 1) / y to get the rounded-up version of x/y. If it's 3/2, then that becomes (3 + 2 - 1) / 2 = 4 / 2 = 2.
You can use the ceil (ceiling) function:
https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil(double)
That will essentially round up to the nearest whole number.
If you can change the datatype to double, following is the best solution -
double x = 3;
double y = 2;
Math.ceil(Math.abs(x/y));
This will give you 2.0
import java.lang.Math;
//round Up Math.ceil(double num)
//round Down Math.floor(double num)
public class RoundOff
{
public static void main(String args[])
{ //since ceil() method takes double datatype value as an argument
//either declare at least one of this variable as double
int x=3;
int y=2; //double y =2;
//or at least cast one of this variable as a (double) before taking division
System.out.print(Math.ceil((double)x/y)); //prints 2.0
//System.out.print(Math.ceil(x/y));
}
}
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:
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)
How could I always round up a double to an int, and never round it down.
I know of Math.round(double), but I want it to always round up.
So if it was 3.2, it gets rounded to 4.
You can use Math.ceil() method.
See JavaDoc link: https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html#ceil(double)
From the docs:
ceil
public static double ceil(double a)
Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. Special cases:
If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
If the argument value is less than zero but greater than -1.0, then the result is negative zero.
Note that the value of Math.ceil(x) is exactly the value of -Math.floor(-x).
Parameters:
a - a value.
Returns:
The smallest (closest to negative infinity) floating-point value that is greater than or equal to the argument and is equal to a mathematical integer.
In simple words,
Math.ceil will always round UP or as said above, in excess.
Math.round will round up or down depending on the decimals.
If the decimal is equal or higher than 5, then it's rounded up.
decimal => 5. (1,5 = 2)
If the decimal is less than 5, then it's rounded down.
decimal < 5. (1,45 = 1)
Examples of Math.ceil and Math.round:
The code Below would return:
Cost, without Ceil 2.2 and with Ceil 3 (int), 3.0 (double). If we round it: 2
int m2 = 2200;
double rate = 1000.0;
int costceil = (int)Math.ceil(m2/rate);
double costdouble = m2/rate;
double costdoubleceil = Math.ceil(m2/rate);
int costrounded = (int)Math.round(m2/rate);
System.out.println("Cost, without Ceil "+costdouble+" and with Ceil "+
costceil+"(int), "+costdoubleceil+"(double). If we round it: "+costrounded);
If we change the value of m2 to for example 2499, the result would be:
Cost, without Ceil 2.499 and with Ceil 3 (int), 3.0 (double). If we round it: 2
If we change the value of m2 to for example 2550, the result would be:
Cost, without Ceil 2.55 and with Ceil 3 (int), 3.0 (double). If we round it: 3
Hope it helps. (Information extracted from previous answers, i just wanted to make it clearer).
tl;dr
BigDecimal( "3.2" ).setScale( 0 , RoundingMode.CEILING )
4
BigDecimal
If you want accuracy rather than performance, avoid floating point technology. That means avoiding float, Float, double, Double. For accuracy, use BigDecimal class.
On a BigDecimal, set the scale, the number of digits to the right of the decimal place. If you want no decimal fraction, set scale to zero. And specify a rounding mode. To always round an fraction upwards, use RoundingMode.CEILING, documented as:
Rounding mode to round towards positive infinity. If the result is positive, behaves as for RoundingMode.UP; if negative, behaves as for RoundingMode.DOWN. Note that this rounding mode never decreases the calculated value. So for example, 1.1 becomes 2, and your 3.2 becomes 4.
BigDecimal bd = new BigDecimal( "3.2" ) ;
BigDecimal bdRounded = bd.setScale( 0 , RoundingMode.CEILING ) ;
String output = bdRounded.toString() ;
System.out.println( "bdRounded.toString(): " + bdRounded ) ; // 4
4
See this code run live at IdeOne.com.
private int roundUP(double d){
double dAbs = Math.abs(d);
int i = (int) dAbs;
double result = dAbs - (double) i;
if(result==0.0){
return (int) d;
}else{
return (int) d<0 ? -(i+1) : i+1;
}
}
Good job ! ;)
My method is relatively simple, hope it works for you.
In my case I have a row of objects that can only hold 3 items and I must adjust the number of rows I have to accommodate the items.
So I have some Double numberOfRows, I then use numberOfRows.intValue() to get an int value for numberOfRows.
if the int value I get is less than numberOfRows, I add 1 to numberOfRows to round it up, else the value I get from numberOfRows.intValue() is the answer I want.
I wrote this simple for loop to test it out:
for(int numberOfItems = 0; numberOfItems < 16; numberOfItems++) {
Double numberOfRows = numberOfItems / 3.0;
System.out.println("Number of rows are: " + numberOfRows);
System.out.println("Number of items are: " + numberOfItems);
if(numberOfRows.intValue() < numberOfRows) {
System.out.println("int number of rows are: " + (numberOfRows.intValue() + 1));
}
else {
System.out.println("int value of rows are: " + numberOfRows.intValue());
}
System.out.println();
System.out.println();
}
Short example without using Math.ceil().
public double roundUp(double d){
return d > (int)d ? (int)d + 1 : d;
}
Exaplanation:
Compare operand to rounded down operand using typecast, if greater return rounded down argument + 1 (means round up) else unchanged operand.
Example in Pseudocode
double x = 3.01
int roundDown = (int)x // roundDown = 3
if(x > roundDown) // 3.01 > 3
return roundDown + 1 // return 3.0 + 1.0 = 4.0
else
return x // x equals roundDown
Anyway you should use Math.ceil(). This is only meant to be a simple example of how you could do it by yourself.
Math.ceil did not work for me. It keeps rounding down when I cast back to long. Below is my hack:
long pages = (userCnt % size) == 0 ? (userCnt / size) : (userCnt / size) + 1;
Simply check if Even or Odd and if Odd, add 1 to the result.
Math.ceil() will give you the closest lowest value if you want it to be rounded to largest closest values you should use Math.floor()
int total = (int) Math.ceil(157/32);
Why does it still return 4? 157/32 = 4.90625, I need to round up, I've looked around and this seems to be the right method.
I tried total as double type, but get 4.0.
What am I doing wrong?
You are doing 157/32 which is dividing two integers with each other, which always result in a rounded down integer. Therefore the (int) Math.ceil(...) isn't doing anything. There are three possible solutions to achieve what you want. I recommend using either option 1 or option 2. Please do NOT use option 0.
Option 0
Convert a and b to a double, and you can use the division and Math.ceil as you wanted it to work. However I strongly discourage the use of this approach, because double division can be imprecise. To read more about imprecision of doubles see this question.
int n = (int) Math.ceil((double) a / b));
Option 1
int n = a / b + ((a % b == 0) ? 0 : 1);
You do a / b with always floor if a and b are both integers. Then you have an inline if-statement which checks whether or not you should ceil instead of floor. So +1 or +0, if there is a remainder with the division you need +1. a % b == 0 checks for the remainder.
Option 2
This option is very short, but maybe for some less intuitive. I think this less intuitive approach would be faster than the double division and comparison approach:
Please note that this doesn't work for b < 0.
int n = (a + b - 1) / b;
To reduce the chance of overflow you could use the following. However please note that it doesn't work for a = 0 and b < 1.
int n = (a - 1) / b + 1;
Explanation behind the "less intuitive approach"
Since dividing two integers in Java (and most other programming languages) will always floor the result. So:
int a, b;
int result = a/b (is the same as floor(a/b) )
But we don't want floor(a/b), but ceil(a/b), and using the definitions and plots from Wikipedia:
With these plots of the floor and ceil functions, you can see the relationship.
You can see that floor(x) <= ceil(x). We need floor(x + s) = ceil(x). So we need to find s. If we take 1/2 <= s < 1 it will be just right (try some numbers and you will see it does, I find it hard myself to prove this). And 1/2 <= (b-1) / b < 1, so
ceil(a/b) = floor(a/b + s)
= floor(a/b + (b-1)/b)
= floor( (a+b-1)/b) )
This is not a real proof, but I hope you're satisfied with it. If someone can explain it better I would appreciate it too. Maybe ask it on MathOverflow.
157/32 is int/int, which results in an int.
Try using the double literal - 157/32d, which is int/double, which results in a double.
157/32 is an integer division because all numerical literals are integers unless otherwise specified with a suffix (d for double l for long)
the division is rounded down (to 4) before it is converted to a double (4.0) which is then rounded up (to 4.0)
if you use a variables you can avoid that
double a1=157;
double a2=32;
int total = (int) Math.ceil(a1/a2);
int total = (int) Math.ceil((double)157/32);
Nobody has mentioned the most intuitive:
int x = (int) Math.round(Math.ceil((double) 157 / 32));
This solution fixes the double division imprecision.
In Java adding a .0 will make it a double...
int total = (int) Math.ceil(157.0 / 32.0);
When dividing two integers, e.g.,
int c = (int) a / (int) b;
the result is an int, the value of which is a divided by b, rounded toward zero. Because the result is already rounded, ceil() doesn't do anything. Note that this rounding is not the same as floor(), which rounds towards negative infinity. So, 3/2 equals 1 (and floor(1.5) equals 1.0, but (-3)/2 equals -1 (but floor(-1.5) equals -2.0).
This is significant because if a/b were always the same as floor(a / (double) b), then you could just implement ceil() of a/b as -( (-a) / b).
The suggestion of getting ceil(a/b) from
int n = (a + b - 1) / b;, which is equivalent to a / b + (b - 1) / b, or (a - 1) / b + 1
works because ceil(a/b) is always one greater than floor(a/b), except when a/b is a whole number. So, you want to bump it to (or past) the next whole number, unless a/b is a whole number. Adding 1 - 1 / b will do this. For whole numbers, it won't quite push them up to the next whole number. For everything else, it will.
Yikes. Hopefully that makes sense. I'm sure there's a more mathematically elegant way to explain it.
Also to convert a number from integer to real number you can add a dot:
int total = (int) Math.ceil(157/32.);
And the result of (157/32.) will be real too. ;)
int total = (int) Math.ceil( (double)157/ (double) 32);
Check the solution below for your question:
int total = (int) Math.ceil(157/32);
Here you should multiply Numerator with 1.0, then it will give your answer.
int total = (int) Math.ceil(157*1.0/32);
Use double to cast like
Math.ceil((double)value) or like
Math.ceil((double)value1/(double)value2);
Java provides only floor division / by default. But we can write ceiling in terms of floor. Let's see:
Any integer y can be written with the form y == q*k+r. According to the definition of floor division (here floor) which rounds off r,
floor(q*k+r, k) == q , where 0 ≤ r ≤ k-1
and of ceiling division (here ceil) which rounds up r₁,
ceil(q*k+r₁, k) == q+1 , where 1 ≤ r₁ ≤ k
where we can substitute r+1 for r₁:
ceil(q*k+r+1, k) == q+1 , where 0 ≤ r ≤ k-1
Then we substitute the first equation into the third for q getting
ceil(q*k+r+1, k) == floor(q*k+r, k) + 1 , where 0 ≤ r ≤ k-1
Finally, given any integer y where y = q*k+r+1 for some q,k,r, we have
ceil(y, k) == floor(y-1, k) + 1
And we are done. Hope this helps.
There are two methods by which you can round up your double value.
Math.ceil
Math.floor
If you want your answer 4.90625 as 4 then you should use Math.floor and if you want your answer 4.90625 as 5 then you can use Math.ceil
You can refer following code for that.
public class TestClass {
public static void main(String[] args) {
int floorValue = (int) Math.floor((double)157 / 32);
int ceilValue = (int) Math.ceil((double)157 / 32);
System.out.println("Floor: "+floorValue);
System.out.println("Ceil: "+ceilValue);
}
}
I know this is an old question but in my opinion, we have a better approach which is using BigDecimal to avoid precision loss. By the way, using this solution we have the possibility to use several rounding and scale strategies.
final var dividend = BigDecimal.valueOf(157);
final var divisor = BigDecimal.valueOf(32);
final var result = dividend.divide(divisor, RoundingMode.CEILING).intValue();
int total = (157-1)/32 + 1
or more general
(a-1)/b +1