JAVA Round to closest number - java

How to round a decimal number to closest "whole" number?

You can try using
float x = (float)Math.ceil(x);
or
float y = (float)Math.round(y);
Also note that I have converted them back to float as there may be a loss of precision when you are converting double to float.

One line answer!
public static long roundToClosestLong(long num, long div) {
return (long) num / div + ((double) (num % div) / div < 0.5 ? 0 : 1);
}

You can use java.lang.Math class for that.
Math#round(double) Will accecpt double as argument and returns long
Math#round(float) Will accecpt float as argument and returns int

You could do:
int result = (int) (yourValue + 0.5);
if you just need simple rounding this is maybe a more performant solution than Math.round(yourValue)

Related

Java ((4-2) / 4) = 0.0 not 0.5 after casting as double

This method has myNumSides equal to 4, myNumSides is a user-inputted. After myAngle being casted as a double it still returns 0.0 instead of 0.5. Why is this?
public double getMyAngle()
{
int n;
n = myNumSides;
double myAngle = (double) ((n - 2) / n);
return myAngle;
}
Output
Please enter number of sides => 4
Please enter length of each side => 100
Your polygon has 4 sides.
Each side of your polygon has a length of 100.0.
The angle of each vertex is 0.0.
In order to get the correct answer, you would have to do the following:
double myAngle = ((n - 2.0) / n);
OR
double myAngle = ((n - 2) / (double)n);
When java executes double myAngle = (double) ((n - 2) / n);, It will first do the division operation and then do the casting operation. In the division operation you are dividing an Integer by an another Integer. So the result of this division also will be an Integer. In your case case, 2/4 = 0.
Correct code would be do the casting first and then division.
double myAngle = ((double)(n - 2) / n);
If you cast a zero to a double, it's still a zero. What you do with the result has no effect on how it's computed.
You have already performed the math as an int, you then cast that int to a double. This widens the value but does not restore the lost precision to the previously computed value, I suggest you just make n a double like
public double getMyAngle() {
double n = myNumSides;
return ((n - 2) / n);
}
You can change your code to:
public double getMyAngle()
{
int n;
n = myNumSides;
double myAngle = (double)(n - 2)/n;
return myAngle;
}
==================
then the answer should be correct!

Round values in java

How will I round
1 < value < 1.5 to 1.5
1.5 < value < 2 to 2
How about
double rounded = Math.ceil(number * 2) / 2;
Since Math.ceil() already returns a double, no need to divide by 2.0d here. This will work fine as long as you're in the range of integers that can be expressed as doubles without losing precision, but beware if you fall out of that range.
public double foo(double x){
int res = Math.round(x);
if(res>x) // x > .5
return res -0.5;
else
return res + 0.5;
}
I havent compiled this but this is pseudocode and should work
Multiply by 2, use Math.ceil(), then divide that result by 2.
public double round(double num)
{
double rounded = (int) (num + 0.4999f);
if(num > rounded)
return rounded + 0.5;
else
return rounded;
}
You can use
double numberGrade = 2.5;
Math.ceil(numberGrade);

Raising a number to a power in Java

Here is my code. For some reason my BMI is not calculated correctly.
When I check the output on a calculator for this : (10/((10/100)^2))) I get 1000, but in my program, I get 5. I'm not sure what I am doing wrong. Here is my code:
import javax.swing.*;
public class BMI {
public static void main(String args[]) {
int height;
int weight;
String getweight;
getweight = JOptionPane.showInputDialog(null, "Please enter your weight in Kilograms");
String getheight;
getheight = JOptionPane.showInputDialog(null, "Please enter your height in Centimeters");
weight = Integer.parseInt(getweight);
height = Integer.parseInt(getheight);
double bmi;
bmi = (weight/((height/100)^2));
JOptionPane.showMessageDialog(null, "Your BMI is: " + bmi);
}
}
^ in java does not mean to raise to a power. It means XOR.
You can use java's Math.pow()
And you might want to consider using double instead of int—that is:
double height;
double weight;
Note that 199/100 evaluates to 1.
we can use
Math.pow(2, 4);
this mean 2 to the power 4 (2^4)
answer = 16
^ is not the operator you want. You are looking for the pow method of java.lang.Math.
You can use Math.pow(value, power).
Example:
Math.pow(23, 5); // 23 to the fifth power
Your calculation is likely the culprit. Try using:
bmi = weight / Math.pow(height / 100.0, 2.0);
Because both height and 100 are integers, you were likely getting the wrong answer when dividing. However, 100.0 is a double. I suggest you make weight a double as well. Also, the ^ operator is not for powers. Use the Math.pow() method instead.
Too late for the OP of course, but still...
Rearranging the expression as:
int bmi = (10000 * weight) / (height * height)
Eliminates all the floating point, and converts a division by a constant to a multiplication, which should execute faster. Integer precision is probably adequate for this application, but if it is not then:
double bmi = (10000.0 * weight) / (height * height)
would still be an improvement.
You should use below method-
Math.pow(double a, double b)
From (https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#pow-double-double-)
Returns the value of the first argument raised to the power of the second argument.
int weight=10;
int height=10;
double bmi;
bmi = weight / Math.pow(height / 100.0, 2.0);
System.out.println("bmi"+(bmi));
double result = bmi * 100;
result = Math.round(result);
result = result / 100;
System.out.println("result"+result);
1) We usually do not use int data types to height, weight, distance,
temperature etc.(variables which can have decimal points)
Therefore height, weight should be double or float.
but double is more accurate than float when you have more decimal points
2) And instead of ^, you can change that calculation as below using Math.pow()
bmi = (weight/(Math.pow(height/100, 2)));
3) Math.pow() method has below definition
Math.pow(double var_1, double var_2);
Example:
i) Math.pow(8, 2) is produced 64 (8 to the power 2)
ii) Math.pow(8.2, 2.1) is produced 82.986813689753 (8.2 to the power 2.1)
I did the benchmarking with Math.pow(x,2) and x*x,
the result is that Math.pow() is easily forty times slower than manually multiplying it by itself, so i don't recommend it for anything where a little bit of performance is required.
Here's the results:
proof_of_work: 19.284756867003345
time for Math.pow(x,2) in ns: 35143
proof_of_work: 19.284756867003345
time for x*x in ns: 884
manual calculation is 39 times faster
and here's the test-code
double r1 = 4.391441320;
long multiply_d1 = System.nanoTime();
double multiply_dr = Math.pow(r1,2);
long multiply_d2 = System.nanoTime();
System.out.println(("proof_of_work: ") + (multiply_dr));
System.out.println(("time for Math.pow(x,2) in ns: ") + (multiply_d2 - multiply_d1));
long multiply_t1 = System.nanoTime();
double multiply_tr = r1*r1;
long multiply_t2 = System.nanoTime();
System.out.println(("proof_of_work: ") + (multiply_tr));
System.out.println(("time for x*x in ns: ") + (multiply_t2 - multiply_t1));
System.out.println(("manual calculation is ") + ((multiply_d2 - multiply_d1) / (multiply_t2 - multiply_t1)) + (" times faster"));
Most efficient solution is
public Float fastPow(Float number, Integer power) {
if (power == 0) {
return 1.0f;
} else if (power % 2 == 1) {
return fastPow(number, power - 1) * number;
} else {
return fastPow(number * number, power / 2);
}
}
Let A is our number and N our power. Then A^2^N = (A^2)^N. And A^N = (A^2)^N/2. The function above reflects this relationship.

How to round integer in java

I want to round the number 1732 to the nearest ten, hundred and thousand. I tried with Math round functions, but it was written only for float and double. How to do this for Integer? Is there any function in java?
What rounding mechanism do you want to use? Here's a primitive approach, for positive numbers:
int roundedNumber = (number + 500) / 1000 * 1000;
This will bring something like 1499 to 1000 and 1500 to 2000.
If you could have negative numbers:
int offset = (number >= 0) ? 500 : -500;
int roundedNumber = (number + offset) / 1000 * 1000;
(int)(Math.round( 1732 / 10.0) * 10)
Math.round(double) takes the double and then rounds up as an nearest integer. So, 1732 will become 173.2 (input parameter) on processing by Math.round(1732 / 10.0). So the method rounds it like 173.0. Then multiplying it with 10 (Math.round( 1732 / 10.0) * 10) gives the rounded down answer, which is 173.0 will then be casted to int.
Use Precision (Apache Commons Math 3.1.1)
Precision.round(double, scale); // return double
Precision.round(float, scale); // return float
Use MathUtils (Apache Commons Math) - Older versions
MathUtils.round(double, scale); // return double
MathUtils.round(float, scale); // return float
scale - The number of digits to the right of the decimal point. (+/-)
Discarded because method round(float,
scale) be used.
Math.round(MathUtils.round(1732, -1)); // nearest ten, 1730
Math.round(MathUtils.round(1732, -2)); // nearest hundred, 1700
Math.round(MathUtils.round(1732, -3)); // nearest thousand, 2000
Better solution
int i = 1732;
MathUtils.round((double) i, -1); // nearest ten, 1730.0
MathUtils.round((double) i, -2); // nearest hundred, 1700.0
MathUtils.round((double) i, -3); // nearest thousand, 2000.0
You could try:
int y = 1732;
int x = y - y % 10;
The result will be 1730.
Edit: This doesn't answer the question. It simply removes part of the number but doesn't "round to the nearest".
At nearest ten:
int i = 1986;
int result;
result = i%10 > 5 ? ((i/10)*10)+10 : (i/10)*10;
(Add zero's at will for hundred and thousand).
why not just check the unit digit...
1. if it is less than or equal to 5, add 0 at the unit position and leave the number as it is.
2. if it is more than 5, increment the tens digit, add 0 at the unit position.
ex: 1736 (since 6 >=5) the rounded number will be 1740.
now for 1432 (since 2 <5 ) the rounded number will be 1430....
I hope this will work... if not than let me know about those cases...
Happy Programming,
very simple. try this
int y = 173256457;int x = (y/10)*10;
Now in this you can replace 10 by 100,1000 and so on....
Its very easy..
int x = 1234;
int y = x - x % 10; //It will give 1230
int y = x - x % 100; //It will give 1200
int y = x - x % 1000; //It will give 1000
The above logic will just convert the last digits to 0. If you want actual round of//
For eg. 1278 this should round off to 1280 because last digit 8 > 5 for this i wrote a function check it out.
private double returnAfterRoundDigitNum(double paramNumber, int noOfDigit)
{
double tempSubtractNum = paramNumber%(10*noOfDigit);
double tempResultNum = (paramNumber - tempSubtractNum);
if(tempSubtractNum >= (5*noOfDigit))
{
tempResultNum = tempResultNum + (10*noOfDigit);
}
return tempResultNum;
}
Here pass 2 parameters one is the number and the other is position till which you have to round off.
Regards,
Abhinav
I usually do it this way:
int num = 1732;
int roundedNum = Math.round((num + 9)/10 * 10);
This will give you 1740 as the result.
Hope this will help.
int val2 = 1732;
val2 = (int)(Math.rint((double) i / 10) * 10);
The output is:1730
Have you looked at the implementation of Mathutils.round() ? It's all based on BigDecimal and string conversions. Hard to imagine many approaches that are less efficient.
Without using any math utils, rounding could be achieved to any unit as below:
double roundValue (double input, double toNearest){
//toNearest is any rounding base like 10, 100 or 1000.
double modValue = input % toNearest;
System.out.println(modValue);
if(modValue == 0d){
roundedValue = input;
}
else
{
roundedValue = ((input - modValue) + toNearest);
}
System.out.println(roundedValue);
return roundedValue;
}

Is there any Java function or util class which does rounding this way: func(3/2) = 2?

Is there any Java function or util class which does rounding this way: func(3/2) = 2
Math.ceil() doesn't help, which by name should have done so. I am aware of BigDecimal, but don't need it.
Math.ceil() will always round up, however you are doing integer division with 3/2. Thus, since in integer division 3/2 = 1 (not 1.5) the ceiling of 1 is 1.
What you would need to do to achieve the results you want is Math.ceil(3/2.0);
By doing the division by a double amount (2.0), you end up doing floating point division instead of integer division. Thus 3/2.0 = 1.5, and the ceil() of 1.5 is always 2.
A bit of black magic, and you can do it all with integers:
// Divide x by n rounding up
int res = (x+n-1)/n
To convert floor division to ceiling division:
(numerator + denominator-1) / denominator
To convert floor division to rounding division:
(numerator + (denominator)/2) / denominator
You can always cast first:
Math.ceil((double)3/2)
In Java, 3/2 = 1 because it uses integer division. There's no function that can "fix" this afterwards. What you have to do is to force a float divison and round up the result:
int result = (int)Math.ceil( ((float)3) / ((float)2) );
Aint this the usual case of integer division? Try Math.Ceil after casting either number to a floating point type.
Many languages "think" like this. If you're dividing an int into an int, then you should get an int (so they truncate and you get 1 as a result).
We all know this is not true, but that's how they work. You can "cheat" them, and do something like casting one of them to a double, or use a double representation: Math.ceil (3.0 / 2) or Math.ceil((double)3/2), as mentioned.
Math.ceil will help, provided you use floating point numbers. The problem is that 3/2, in integer division, is 1. By the time the value gets to whatever function, be it Math.ceil or something else, the value is simply 1. Any trailing decimal portion is gone.
if (a % b == 0)
{
return (a / b);
}
else
{
return (a / b) + 1;
}
Exploits integer division to do what you want. I don't know of a math function that does this, but why not roll your own?
below fragment works with negative integers as well:
public static int divRoundUp(int x, int n) {
if (n<=0) throw new RuntimeException("conceived wt. pos. dividers (was:"+n+")");
int ret = (x+(n-1)*(x>0?1:0))/n;
return ret;
}
If you want to just divide by 2, you can do:
n - n / 2
And in general:
(n - 1) / d + 1 == (n + d - 1) / d
This holds for non-negative integers. How to extend it to negative integers depends on what you mean with "does rounding this way". Integer division is rounded towards zero, whereas Math.ceil() rounds up and Math.floor() rounds down. For example n / 2 != (int) Math.floor(n / 2.0) for n == -5.
If you want to always round up, you can use Math.ceil() as in this answer.
If you really want to avoid using ceil and casting, here is a little method that accomplishes the same thing.
public int findCeil(int X, int Y) {
if (X % Y == 0){
return X / Y;
} else {
return X / Y + 1;
}
}
I like Randy Proctor's answer the best. Here in more detail:
If you want to do real rounding (i.e. 3/2 -> 2, but 17 / 7 -> 2) with integers > 0:
use (dividend + (divisor / 2)) / divisor instead of dividend / divisor.
If dividend can be any integer (i.e. negative allowed):
(dividend >= 0) ? ((dividend + divisor / 2) / divisor) : ((dividend - divisor / 2) / divisor).
If dividend is any integer and divisor any integer but 0:
(dividend >= 0) ? ((dividend + Math.abs(divisor) / 2) / divisor) : ((dividend - Math.abs(divisor) / 2) / divisor).
(Note that the addition and substraction can cause a wraparound that otherwise wouldn't occur, rendering the result incorrect.)
Here is a method I created to handle int division without using Math Round and casting to float. This works for positive and negative numbers. It works by adding half of the denominator to offset the rounding down
public static int div_Int(int num, int den){
if(num > 0 && den > 0 || num < 0 && den < 0 ){
return ((2*num)+ den)/(2*den);
}else{
return ((2*num)- den)/(2*den);
}
}
Have you tried Math.floor() ?

Categories