How to round integer in java - 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;
}

Related

Generate Random X.XXX numbers between [-2, 2]

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 need help making change in java. It doesnt give out change correctly

Hi I'm trying to make a method that gives you change in Hundreds, Fifties, Twenties, Tens, Fives, ones as well as quarters dimes and nickels. the user gives input and its supposed to look something like this: 6.87 1 five 1 one 3 quarters 1 dime 2 pennies
So far I have this as my code:
import java.util.Scanner;
/**
*
* #author Cjespinomartine
*/
public class Assignment04 {
public static void main(String[]args) {
Scanner stdin = new Scanner(System.in);
System.out.println("Enter your amount");
double amount = stdin.nextDouble();
double remainder = Math.round(amount * 100);
double hundreds = remainder / 1000;
remainder = remainder / 1000;
double fifties = remainder / 500;
remainder = remainder / 500;
double twenties = remainder / 200;
remainder = remainder % 200;
/*
double fives = remainder / 5;
remainder = remainder % 5;
double ones = remainder / 1;
remainder = remainder % 1;
double quarters = remainder / .25;
remainder = remainder % .25;
double dimes = remainder / .10;
remainder = remainder %10;
double nickels = remainder / .5;
remainder = remainder % .5;
double pennies = remainder;
*/
System.out.println(hundreds + "hundred/s");
System.out.println(fifties + "fiftie/s");
System.out.println(twenties + "twentie/s");
/* System.out.println(fives + "five/s");
System.out.println(ones + "one/s");
System.out.println(quarters + "quarter/s");
System.out.println(dimes + "dime/s");
System.out.println(nickels + "nickel/s");
System.out.println(pennies + "cent/s");
*/
}
}
It doesn't give out change in order it just gives out hundreds. I commented some of the change because I'm trying to get the math right. I think the assignment required if and else if so if it does can you help me out with where I put it. any help will mean a lot i'm very stuck thank you.
There are a few things wrong.
The first issue is your initial handling of remainder – you're multiplying by 100, so if input is 1274.56, you end up with 127456 (ignoring floating point problems which are valid but I'll stay focused on this first point). The output of Math.round() is either an int or long, but definitely not a double so you're adding confusion for yourself by storing it as a double – instead, store the result as long. From there, when you calculate hundreds, you need to divide by 10,000 not 1,000. Also, store that as an int, not a double. Here's what that would look like:
long remainder = Math.round(1274.56 * 100);
int hundreds = (int) remainder / 10000;
System.out.println("hundreds: " + hundreds);
The above prints out "12" for hundreds, which is what you want.
The second issue is how you're calculating remainder. You want everything that's "left over" from the prior calculation which you do by using % (modulus operator), and also use 10,000 instead of 1,000. For the hundreds case, it would be this:
remainder = remainder % 10000;
System.out.println("remainder: " + remainder);
The above code would print this:
remainder: 7456
This should give you enough to get the rest of your math working properly.
remainder = remainder / 1000; is wrong. What you want is the remainder after you've taken out all the hundreds. remainder = remainder % 1000; -looks like the commented out ones are correct...
Also don't use floating point types for money. Google will give you a thousand reasons why.

How to round double to nearest whole number and return it as Integer

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

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.

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