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);
Related
Anyone got an idea of how to achieve this. I've tried the usual formula but I'm only getting positive numbers <= 10:
Double.MIN_VALUE + Math.random() * ((Double.MAX_VALUE - Double.MIN_VALUE) + 1)
You could do this
private static final Random rand = new Random();
public static double getRandomDouble() {
while(true) {
double d = Double.longBitsToDouble(rand.nextLong());
if (d < Double.POSITIVE_INFINITY && d > Double.NEGATIVE_INFINITY)
return d;
}
}
This will return any finite double with equal probability.
You can't just the the formula above as the (Double.MAX_VALUE - (-Double.MAX_VALUE)) overflows to infinity. i.e. the range for all positive and negative double values is too large to store in a double.
double d = Math.random() * Double.MAX_VALUE;
return Math.random() < 0.5 ? d : 0-d;
I have the below codes round the forward rate to 15 decimal place. When _ForwardRate is 13,555.0, the result return is wrong.
public double round(double Number, int Decimal_Place) {
if (Number==0) return 0;
double _plug = 0.000001;
if (Number < 0) {
_plug = -0.000001;
}
//Sometime a number is rounded down to 2.22499999999 by java.
//Actual precision is 2.245. Without this plug, a 2 dp rounding result
//in 2.22 when it should be 2.23
double _newNumber = Number;
if (Decimal_Place==2) {
_newNumber = _newNumber+_plug;
}
double _number_abs = Math.abs(_newNumber);
double _factor = Math.pow(10, Decimal_Place);
double _rd = Math.round(_number_abs * _factor);
double _r = _rd/_factor;
if (Number <= 0)
_r = _r * -1;
return _r;
}
Double _ForwardRate = getForward_rate();
BigDecimal _fwdrate_bd = BigDecimal.valueOf(_ForwardRate.doubleValue());
_ForwardRate = round(new Double(_fwdrate_bd.doubleValue()), 15);
Current result
9,223.372036854777
Expected result
13,555.000000000000000
Your problem is that Math.round(double a) returns long, and you're overflowing.
One easy way to do this, is to use BigDecimal:
public static double round(double number, int decimalPlaces) {
return BigDecimal.valueOf(number)
.setScale(decimalPlaces, RoundingMode.HALF_UP)
.doubleValue();
}
This allows you to control the rounding mode. Note that the rounding done by Math.round() is a HALF_CEILING which isn't supported by setScale().
You might want to consider doing all you math using BigDecimal, if you need that level of precision.
Consider:
double _number_abs = Math.abs(_newNumber);
At this point, _number_abs contains the value 13555.0
double _factor = Math.pow(10, Decimal_Place);
Now _factor contains 1.0E15
double _rd = Math.round(_number_abs * _factor);
According to the Javadoc
Math.round() Returns the closest long to the argument, with ties rounding to positive infinity.
Since _number_abs * _factor is 1.3555E19, which is larger than Long.MAX_VALUE, the result is Long.MAX_VALUE, i.e. the "closest" Long to the given value.
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)
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!
Let suppose that I have double x. I would return nearest whole number of x. For example:
if x = 6.001 I would return 6
if x = 5.999 I would return 6
I suppose that I should use Math.ceil and Math.floor functions. But I don't know how return nearest whole number...
For your example, it seems that you want to use Math.rint(). It will return the closest integer value given a double.
int valueX = (int) Math.rint(x);
int valueY = (int) Math.rint(y);
public static void main(String[] args) {
double x = 6.001;
double y = 5.999;
System.out.println(Math.round(x)); //outputs 6
System.out.println(Math.round(y)); //outputs 6
}
The simplest method you get taught in most basic computer science classes is probably to add 0.5 (or subtract it, if your double is below 0) and simply cast it to int.
// for the simple case
double someDouble = 6.0001;
int someInt = (int) (someDouble + 0.5);
// negative case
double negativeDouble = -5.6;
int negativeInt = (int) (negativeDouble - 0.5);
// general case
double unknownDouble = (Math.random() - 0.5) * 10;
int unknownInt = (int) (unknownDouble + (unknownDouble < 0? -0.5 : 0.5));
int a = (int) Math.round(doubleVar);
This will round it and cast it to an int.
System.out.print(Math.round(totalCost));
Simple
Math.round() method in Java returns the closed int or long as per the argument
Math.round(0.48) = 0
Math.round(85.6) = 86
Similarly,
Math.ceil gives the smallest integer as per the argument.
Math.round(0.48) = 0
Math.round(85.6) = 85
Math.floor gives the largest integer as per the argument.
Math.round(0.48) = 1
Math.round(85.6) = 86