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.
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.
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);
So it's easy to round the tenths place with just doing something like:
int y;
double x = 2.5;
y = (int) (x+.5);
but how would you go about rounding to the hundredths or even thousands place without using Math.round()?
You can multiply the original number by a power of 10 so that the desired place to round is in the unit's place, apply the "add half and round" method you already have, then divide the same power of 10, so the resulting number is now back to the original scale.
For hundredths:
Declare y to be a double. This is so that rounding 2.125 to the hundredths' place will result in 2.13, not 2.
Multiply the x value by 100.0.
Add 0.5.
Cast to int. (Or long for more precision.)
Divide by 100.0.
Ex.: Rounding 2.125 to the hundredths' place.
1. 2.125 * 100.0 is 212.5.
2. 212.5 + 0.5 is 213.0.
3. 213.0 cast to int is 213.
4. 213 divided by 100.0 is 2.13.
For thousandths, the procedure is the same, except that 100.0 is replaced by 1000.0.
The above method is subject to floating-point errors due to the finite precision of the double floating-point type.
You can also convert your value to a BigDecimal. Then you can use BigDecimal's round method. It takes a MathContext that allows you directly to round to the desired precision.
public class Decimal {
public static void main(String[] args) {
double xd = 2.125;
double mult = xd * 100.0;
double add = mult + 0.5;
int reuslts = (int) add;
double result = reuslts / 100.0;
System.out.println(result);// 2.13
}
}
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);
I have to write a program with the following requirements:
I have a variable of type float, say float a = 3333.333f;
I have a variable of type int, say int b = 9999;
When I perform a*b in calculator, the result will be 33329996.667
After rounding up the decimals to 2 places, I want to print the value as 33329996.67 in java. I tried with long, double, float, big decimal, But couldnt succeed.
Can anyone please help me solving this?
float only has 7 digits of precision, so its not a good choice for a result with more than 7 digits. double has up to 16 digits of accuracy and is a better choice.
double a = 3333.333;
int b = 9999;
System.out.printf("%.2f", a * b);
prints
33329996.67
To determine the number of digits after the comma you have to apply a little trick:
First shift the comma to the right for the amount of digits you want to have, then cut the whole number e.g. with Math.ceil(float f) and then shift the comma back to the left.
That will illustrate that:
float f = 33329996.667;
float f2 = Math.ceil((f * 100)) / 100;
f2 now has the value 33329996.67.
Hope this helps.
EDIT: For formatting have a look here