I am making a lottery type game and using Math.random() for the numbers. I want it to always print out what number you got in relation to 0 - 100 (so if Math.random outputted 0.03454 and the number to win was below 0.05, it would set the text of a label to 5). How would you make it round to just a 0.00 number?
Here is some of the code if you want to see what I mean.
public void lotterymath()
{
double x = Math.random();
System.out.println(x);
if (x <= 0.02)
output.setText("you win " + x);
else
output.setText( "you lost " + x);
}
I also have a button below that calls lotterymath() by the way :)
Edit: misread original post:
You will want to multiply by 100, and then cast to an int to truncate it, or Math.round it instead:
System.out.println(Math.round(x*100)); // rounds up or down
or
System.out.println((int) (x*100));
Original:
Use String.format(String, Object...):
System.out.println(String.format("%.2f", x));
The %.2f is a format string.
Have you tried
Math.round(x)
Checkout this link for the documentation: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round(double)
EDIT:
I might not have fully understanded your question, but I think if you use
Math.round(Math.random*100)
You'll get a number between 0 and 100.
I prefer to use BigDecimal when dealing with floating point numbers
BigDecimal myRounded = new BigDeicmal(Math.random()).setScale(2, BigDecimal.ROUND_HALF_UP);
Since Math.random() returns a double between 0.0 to 1.0, you can just multiply the result with 100. So 0.0 * 100 = 0, 1.0 * 100 = 100, and everything in between will always be between 0 and 100.
Use Math.round() to get a full integer number. So if the random number is 0.03454, multiplied by 100 = 3.454. Round it to get 3.
correct:
int var = (int)Math.round(Math.random()*100)
INCORRECT:
int var = Math.round(Math.random()*100)
you need to downcast to integer before assign to integer variable in order to don't get an error like this:
error: incompatible types: possible lossy conversion from long to int
int var = Math.round( Math.random() * 3);
^
When you create the variable multiply it by 100 like so:
double a = Math.random()*100;
then when you have to print it put an (int) before the variable just like down here:
System.out.print((int)a);
Related
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.
Had a look around the questions on this site and could not quite find the answer I was looking for about type casting the Math.random() method from double to int.
My question is, why does Math.random only return a 0 without parentheses whereas it returns random numbers when it is contained within the parentheses?
The first part of code returns 0:
int number;
number = (int) Math.random() * 10;
System.out.println("\nThe random number is " + number);
This code works however:
int number;
number = (int) (Math.random() * 10);
System.out.println("\nThe random number is " + number);
It should be noted I have seen a few different pieces of code on typecasting whereby some programmers seem to use both ways of casting.
This code:
number = (int) Math.random() * 10;
first calculates this:
(int) Math.random()
Since Math.random() returns a number from 0 up to but not including 1, if you cast it to int, it will round down to 0. Then when you multiply 10 to 0 you get 0.
Math.random() returns a number from 0 to 1. You want to cast the result of (Math.random()*10) to int, not the number you get from Math.random itself.
Numbers get rounded down. Therefore, for example, 0.3, which you can get from Math.random, gets rounded to 0. Again, you want to round the result of 0.3 times 10, which is 3. The parenthesis is important.
This is the code i am using to calculate a percentage and round it to 2 decimal places. However, at the moment, the result comes out as 45.0% rather than 45.33%
int one = 432;
int rolls = 953;
double test1 = 100 * one / rolls;
double finalValue1 = Math.round( test1 * 100.0 ) / 100.0;
Why are no decimal places showing?
as you are multiplying integers the result of test1 is integer
so you have to say
double test1= 100.0*one/rolls; or
double test1=(double)100*one/rolls
You could use String.format("%.2f",test1). If you use round, then java would round the the integer value. Thus, formatting it this way would give you the answer you seek.
The problem is with the following line:
double test1 = 100 * one / rolls;
That is because 100, one, and rolls are of type int.
When you do 100 * one, that will result in 43200. Then, we have to execute the rest of the calculation... 43200 / 953 would actually equal 45.330535152, but because these are both of type int the result will be 45. Making test1 = 45. Since test one is a double, it will actually be 45.0.
The next calculation, which uses test1 will be off because of the above, resulting in "no decimal value".
To fix this, you can change the type of one and rolls to double.
You have two problems.
First and foremost, you are performing integer division
double test1 = 100 * one / rolls;
100, one and rolls are all int. This means the result is an integer, regardless of what you've declared the return type to be. This is covered in the SO question Why the result of 1/3=0 in java?:
the result variable as double just causes an implicit conversion to occur after division.
If you want doubles, use doubles:
double one = 432.0;
double rolls = 953.0;
After fixing that, your division of Math.round( test1 * 100.0 ) / 100.0; will produce a double, but probably with more than two places of precision. It's unclear at that point if you want further rounding to a specific precision, but if you only wanted to print the two digits after the decimal you could use:
System.out.printf("%.2f", finalValue1);
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()
I want to take two decimal places only for a float without rounding off. eg. 4.21777 should be 4.21 and not 4.22. How do I do this?
A simple answer:
double x = 4.21777;
double y = Math.floor(x * 100) / 100;
Subtract 0.005 and then round. For example if you just want to print the number you can use a format of %f6.2 and the value x-0.005.
float f = 4.21777 * 100;
int solution = (int)f;
f = solution/100;
This should work ;)
Explanation: By multiplying with 100, you will get 421.777, which, castet to int, is being rounded down to 421. Now divided by 100 returns its actual value.