dividing floats and rounding to int in java [duplicate] - java

How to round up a decimal number to a whole number.
3.50 => 4
4.5 => 5
3.4 => 3
How do you do this in Java? Thanks!

With the standard rounding function? Math.round()
There's also Math.floor() and Math.ceil(), depending on what you need.

You can use
int i = Math.round(f);
long l = Math.round(d);
where f and d are of type float and double, respectively.

And if you're working with only positive numbers, you can also use int i = (int)(d + 0.5).
EDIT: if you want to round negative numbers up (towards positive infinity, such that -5.4 becomes -5, for example), you can use this as well. If you want to round to the higher magnitude (rounding -5.4 to -6), you would be well advised to use some other function put forth by another answer.

Java provides a few functions in the Math class to do this. For your case, try Math.ceil(4.5) which will return 5.

new BigDecimal(3.4);
Integer result = BigDecimal.ROUND_HALF_UP;
Or
Int i = (int)(202.22d);

Using Math.max you can do it like this:
(int) Math.max(1, (long) Math.ceil((double) (34) / 25)
This would give you 2

Related

How to get java to produce decimal points while dividing

I'm making a basic calculator where you can plus, times, divide and minus as i was experimenting to see if it worked i noticed that instead of 5 divided by being equal to 1.25 it only displayed 1.
Here's the code i use to handle the math problems:
if (box.getSelectedItem().equals(divide)){
JOptionPane.showMessageDialog(null, Integer.parseInt(first.getText()) / Integer.parseInt(second.getText()), "Answer", -1);
main(args);
}
Is there code that displays the decimal points as well?
Since you are using Integer,it is happening.
Use Double to preserve decimals.
In your case,use
Double.parseDouble(first.getText()) / Double.parseDouble(second.getText())
Integer division will give you Integer. Try using Double or BigDecimal data type.
You need to do the casting
(double)parseInt(first.getText()) / (double)parseInt(second.getText())
Int/Int will give you an Integer. So you need to cast it to Double to get the result in decimal.
EDIT:
If you dont want to show decimal when the result is a whole number then you need to check it like this:
Double res = (double)parseInt(first.getText()) / (double)parseInt(second.getText())
Integer x;
if(res % 1 == 0)
{
x = (int)res
}

How can I show up to 2 decimal places without rounding off?

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.

different result in java how can it be rectified

Simple calculation gives different result in java.
int a=5363/12*5;
out.println(a);// result is 2230
But actually result should be 2234.5
How can this java result be rectified?
Two issues:
The expression 5363/12*5 gives an integer result (in particular, the division is integer).
The variable a is of type int (integer).
To fix:
double a=5363.0/12*5;
out.println(a);
Note that in general you can't expect to get exact results when using floating-point arithmetic. The following is a very good read: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
5363, 12, and 5 are all being interpreted as ints. the calculation actually being performed here is:
5363/12 = 446.9… - truncated to the int value 446
446 * 5 = 2230
Try specifying a as a float, and indicate that the numbers in the calculation are also created as floats:
float a = 5363f/12f*5f
Take a as double.
Taking a as int will round it to the integer.
Because your all the literal numbers in the right hand side are integers (e.g. 5363 as opposed to 5363.0) expression is being calculated using integer arithmetic semantics i.e. / does whole number division. Thus 5262/12 equals 446 and 446*5 equals 2230. Also your variable a is an int which can only ever hold an integer value.
To fix this you need to do two things. Change the type of a to a decimal type e.g. float or double b) have at least one of 5363 and 12 represented as a decimal type e.g.
double a= 5363.0/12.0*5
Instead of using double you can re-order your expression.
Assuming 5363/12*5 = 5363*5/12 this will give you a closer answer. You have commented you want to round the result so instead you have to add half the value you are dividing by.
int a = (5363 * 5 + /* for rounding */ 6) / 12;
System.out.println(a);
prints
2235
An int is an Integer - nothing after the ..
You should be using
double a = 5363d/12*5;
It seems it has some int/double rounding issue:
double a=((double)5363/12)*5;
System.out.println("VALUE: "+a);
Prints:
VALUE: 2234.5833333333335
Edit: rounding the result to an integer value:
double a=((double)5363/12)*5;
long b=Math.round(a); //you can cast it to an int type if needed
System.out.println("ROUNDED: "+b);
Prints:
ROUNDED: 2235
Use double
double a = 5363/12*5;
System.out.println(a);
or
cast the integer, to prevent loss or precision.
int a = ((int) 5363/12*5);
System.out.println(a);

Understanding Casting in Java

this is my first post here and i like to thank all the people that can help me with this simple question: how the casting works in java?
I made this very simple class:
public class test {
public static void main ( String[] args )
{
System.out.println((short)(1/3));
System.out.println((int)(1/3));
System.out.println((float)(1/3));
System.out.println((double)(1/3));
}
}
and this piece of software gives me this output when executed ( official JDK 6 u26 on a 32 bit machine under linux )
0
0
0.0
0.0
the problem, or the thing that i don't understand if you would, is that the last 2 results are 0.0, i was expecting something like 0.3333333, but apparently the cast works in another way: how?
thanks
PS
I'm not so familiar with the english language, if i made some errors i apologize for this
First, the expression 1/3 is executed. This expression means "integer division of 1 by 3". And its result is the integer 0. Then this result (0) is cast to a double (or float). And of course it leads to 0.0.
You must cast one of the operands of the division to a double (or float) to transform it into a double division:
double d = ((double) 1) / 3;
or simply write
1.0 / 3
If you use the operator / on integer values, the result will be typed as an integer.
You will have to force either 1 or 3 to a floating point value - try writing 1.0/3 instead of 1/3.
In the last 2 cases you first compute 1/3, which is 0. Then you cast it to a float/double.
Use:
((float)1)/3
int is coverted into double.
(1/3) is of type int so answer will be 0.
Now 0 is casted to double or float so it has become 0.0
You need to cast the operands, not the result. This will yield the output you expected:
System.out.println(((short) 1 / (short) 3));
System.out.println((1 / 3));
System.out.println(((float) 1 / (float) 3));
System.out.println(((double) 1 / (double) 3));
Because you have the 1/3 in parentheses, it uses integer division then casts to the type specified. It would evaluate to .3333333 if you used 1.0/3.0 or (float)1/3. 1 and 3 are integer literals, so results from division will be truncated. To use float and double literals put an f or d at the end of the number (1.0f, 1.0d). Casting affects the value after it, so if your value is in parentheses, it will evaluate that, then make the cast.

Java using Mod floats

I am working on an exercise in Java. I am supposed to use / and % to extract digits from a number. The number would be something like 1349.9431. The output would be something like:
1349.9431
1349.943
1349.94
1349.9
I know this is a strange way to do but the lab exercise requires it.
Let's think about what you know. Let say you have the number 12345. What's the result of dividing 12345 by 10? What's the result of taking 12345 mod 10?
Now think about 0.12345. What's the result of multiplying that by 10? What's the result of that mod 10?
The key is in those answers.
if x is your number you should be able to do something like x - x%0.1 to get the 1349.9, then x - x%.0.01 to get 1349.94 and so on. I'm not sure though, doing mod on floats is kind of unusual to begin with, but I think it should work that way.
x - x%10 would definetly get you 1340 and x - x%100 = 1300 for sure.
Well the work will be done in background anyway, so why even bother, just print it.
float dv = 1349.9431f;
System.out.printf("%8.3f %8.2f %8.1f", dv, dv, dv);
Alternatively this could be archived with:
float dv = 1349.9431f;
System.out.println(String.format("%8.3f %8.2f %8.1f", dv, dv, dv));
This is a homework question so doing something the way you would actually do in the real world (i.e. using the format method of String as Margus did) isn't allowed. I can see three constraints on any answer given what is contained in your question (if these aren't actually constraints you need to reword your question!)
Must accept a float as an input (and, if possible, use floats exclusively)
Must use the remainder (%) and division (/) operator
Input float must be able to have four digits before and after the decimal point and still give the correct answer.
Constraint 1. is a total pain because you're going to hit your head on floating point precision quite easily if you have to use a number with four digits before and after the decimal point.
float inputNumber = 1234.5678f;
System.out.println(inputNumber % 0.1);
prints "0.06774902343743147"
casting the input float to a double casuses more headaches:
float one = 1234.5678f;
double two = (double) one;
prints "1234.5677490234375" (note: rounding off the answer will get you 1234.5677, which != 1234.5678)
To be honest, this had me really stumped, I spent way too much time trying to figure out how to get around the precision issue. I couldn't find a way to make this program work for 1234.5678f, but it does work for the asker's value of 1349.9431f.
float input = 1349.9431f;
float inputCopy = input;
int numberOfDecimalPoints = 0;
while(inputCopy != (int) inputCopy)
{
inputCopy = inputCopy * 10;
numberOfDecimalPoints++;
}
double inputDouble = (double) input;
double test = inputDouble * Math.pow(10, numberOfDecimalPoints);
long inputLong = Math.round(test);
System.out.println(input);
for(int divisor = 10; divisor < Math.pow(10, numberOfDecimalPoints); divisor = divisor * 10)
{
long printMe = inputLong - (inputLong % divisor);
System.out.println(printMe / Math.pow(10, numberOfDecimalPoints));
}
Of my three constraints, I've satisfied 1 (kind of), 2 but not 3 as it is highly value-dependent.
I'm very interested to see what other SO people can come up with. If the asker has parsed the instructions correctly, it's a very poor exercise, IMO.

Categories