I have this:
return ((Double) Math.ceil(Integer.parseInt(matcher.group()) / 10)).intValue();
I need a number even though the decimal number places below 5, be rouding up.
Using this code, I have these examples:
((Double) Math.ceil(14 / 10).intValue() = 1
((Double) Math.ceil(26 / 10).intValue() = 3
((Double) Math.ceil(25 / 10).intValue() = 3
I need:
((Double) Math.ceil(14 / 10).intValue() = 2
((Double) Math.ceil(26 / 10).intValue() = 3
((Double) Math.ceil(25 / 10).intValue() = 3
Dividing integers gives you integers. There is nothing for Math.ceil() to do, because the number you get isn't 1.4, it's 1. Convert at least one of your numbers to double before dividing:
e.g.
((Double) Math.ceil(Integer.parseInt(matcher.group()) / 10.)).intValue();
or
((Double) Math.ceil(Double.parseDouble(matcher.group()) / 10.)).intValue();
Change you int division to double division, for example as 14 / 10D.
Currently your 14/10 results in 1...
return (int) Math.ceil(Integer.parseInt(matcher.group()) / 10.0));
Also take care not to use integer division, 26/10 = 2.
Related
x = rd.nextInt((4000) - 2000) / 1000.0;
This is generating numbers between [0, 2] to the thousandth decimal which is what I want, I just also need negative number so the range of numbers generated is between [-2, 2].
The problem you are facing is integer arithmetic, which truncates the fractional part of the result. Use rd.nextDouble() instead so the arithmetic results are double, which retains the fractional part.
However, to round to 1/100ths, you can use integer arthmetic to your advantage.
Your question has the text to the hundredth decimal, so here's that solution:
x = (int)(((rd.nextDouble() * 4) - 2) * 100) / 100d;
But your title mentions X.XXX, so here's that solution:
x = (int)(((rd.nextDouble() * 4) - 2) * 1000) / 1000d;
To unravel what's going on here:
generate random double between 0.000000 and 1.000000
multiply by the scale of the range, so we get a number between 0.000000 and 4.000000
subtract 2, so we get a number between -2.000000 and 2.000000
multiply by 1000, so we get a number between -2000.000000 and 2000.000000
cast to int to truncate the fraction, so we get a int between -2000 and 2000
divide by 1000d (which is a double), so we get a double between -2.000 and 2.000
Floating point numbers do not always have a precise number of digits. Also, the third decimal place is called thousandths (the hundredth decimal would be the second digit after the .). I think you know this because you are dividing by a thousand. So, step one: generate a single random value between 0 and 4 as a double. Step two: Subtract two and convert to a formatted String (so you can control the number of digits).
double d = (rd.nextDouble() * 4) - 2;
String x = String.format("%.3f", d);
You can generate a random float and then use a modulo to truncate it to the hundredth decimal place.
int min = -2;
int max = 2;
Random rand = new Random();
float ret = rand.nextFloat() * (max - min) + min;
return ret - (ret % 0.01);
You can generate random number on a range [0,4] and then simply subtract 2 from the result:
x = (rd.nextInt(4000) / 1000.0) - 2;
I know perhaps is stupid question but I don 't understand what is wrong in the following operation:
value = 8.14
double netvalue = value / (1 + 23 / 100);
and the result is:
netvalue = 8.14
Division has precedence over addition, so
1 + 23 / 100 is evaluated as 1 + (23/100) which is 1 + 0 (23/100 is 0 since it is int division, so the result is an int), so you are dividing value by 1.
You can change 23 to 23.0 to achieve floating point division :
double netvalue = value / (1 + 23.0 / 100);
Or you can simply divide by 1.23 :
double netvalue = value / 1.23;
Let understand this
double netvalue = value / (1 + 23 / 100);
the first thing evaluated is 23/100 gives 0
and 1+ 0 = 1
and finally double netvalue = 8.14/1; gives 8.14
I am trying compute average of two double value, but it dose not work truly. I think it is "rounding error" am I right? and how can I fix it?
point.get(0)=1
point.get(1)=4
double Average = (double)(point.get(0) + point.get(1) / 2);
Output:
Average: 3.0
Why?
double Average = (double)(point.get(0) + point.get(1) / 2);
is executed as
Average = (double)(1 + 4/2) = (double) (1+2) = 3.0
Problem
Divison(/) has higher precedence than addition(+)
Fix
You need to add brackets for proper calculation:
double Average = (double)((point.get(0) + point.get(1)) / 2);
should execute as:
Average = (double)((1 + 4)/2) = (double) (5/2) = 2.5
double Average = (double)(point.get(0) + point.get(1) / 2)
Operator precedence trouble. Try this:
double Average = (point.get(0) + point.get(1)) / 2.0;
This has to do with the order of operators - the / has a higher precedence than +, so you are actually getting 1 + (4/2) which does equal 3.
Try this instead:
double Average = (double)((point.get(0) + point.get(1)) / 2);
The extra brackets will correct your issue.
Division takes precedence over addition. Hence,
Average = (double)(1 + 4/2) = (double) (1+2) = 3.0
You should probably make it more like
Average = (double)((1+4)/2)
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
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() ?