Decimal format in Java? - java

can someone explain to me why the output for this:
double y = 15/7;
DecimalFormat first = new DecimalFormat("#.###");
System.out.println(y);
String format_string = first.format(y);
System.out.println(format_string);
Is this:
2.0
2
(Which is wrong)
However, when I change 15/7 to
15.0/7.0
It gives me the correct answer
2.142857142857143
2.143
Explanation please?
Thank you!

Numbers without a dot are Integers so 15/7 is an integer-operation and the result is 2 (divistion without remainder). Afterwards it gets converted to a double but keaps it's value of 2 (conversion after finishing the operation).
Numbers with dots are doubles in the first place so 15.0/7.0 is a double-operation and leads to the result you want to have (floating point division).

Replace
double y = 15/7;
with
double y = 15.0/7;
When dividing two int, you get an int.
See specification :
Integer division rounds toward 0. That is, the quotient produced for
operands n and d that are integers after binary numeric promotion
(§5.6.2) is an integer value q whose magnitude is as large as possible
while satisfying |d · q| ≤ |n|. Moreover, q is positive when |n| ≥ |d|
and n and d have the same sign, but q is negative when |n| ≥ |d| and n
and d have opposite signs.
You convert it to a double by storing it in a double variable but that's too late : you can't get the lost precision back. The solution is to have one of the operands being a double so that you get a double when dividing.

Division of two integers always results in integer - that's why you get 2 (2.0 after formatting).
Division of at least one double gives you double
In your case 15/7 is a division of two integers and the result is an integer (incorrect result). If you change to 15/7.0 or 15.0/7 or 15.0/7.0 your result will be double (correct result)

15/7 performs an integer division, which rounds down to the nearest integer.
15/7 = 2 + 1/7 -> gets rounded to 2
It doesn't matter that you defined y as a double, the division didn't take that into account, since it was using 2 integer literals.

That's because 15 / 7 is 2 as it is returning the integer part of the dividing operation. If you need float values operations, do something like this: 15f / 7.

Both of the values are integers, so they are rounded down to 7. As the result of integer division is an integer you need to make sure you divide doubles / floats as the results of these divisions are doubles / floats which can deal with the decimal parts of the numbers
Even though you specified a double to put the result of the division into what you are actually putting in is an integer, dividing a double means the result is a double and so the answer contains the correct results.

Related

Difference between number/10 and number*0.1 in java

I've been working on an interview question for 1.5 hours and could not find the bug in my Java program.
And then I found what the problem was, which I don't understand (don't pay attention to the values, there were others, it's about the types):
int size=100;
Integer a=12;
if(a >= size/10)...
//didn't work
is different than
if(a >= size*0.1)...
//worked
I understand that there is a conversion, but still, how is it possible that with a=12, if(a>=size/10) returns false?
Why is that?
/10 is integer division. While *0.1 first converts the first operand to a double and performs a floating point multiplication.
If you use the /10, and the operand is 14, it will result in 1 indeed, 14/10=1.4 but integer division rounds this down. Thus 29/10=2.
If you use *0.1, the Java compiler will first convert the value of size to a double, thus 14.0 and then muliplies it with 0.1 resulting in 1.4.
On the other hand it's not all beaty that comes out of floating points. float and double can't represent every integer, and round off after computation.
For the given values for size however, it will result in the effect because 100 is a multiple of 10 and a float or double is capable of representing any integer value in the range from zero to hundred.
Finally /10 is not always an integer division: if the first operand is a floating point (e.g. 14.0d/10), the compiler will convert this to a floating point division.
Short version:
int/int is an integer division that rounds down to the nearest (lower) integer.
int*double is a double multiplication that - with rounding off errors - results in the floating point value, nearest to the correct result (with decimal digits).
I just tested here:
public class a {
public static void main(String[] args) {
int size = 100;
int a = 12;
System.out.println((a >= size / 10) ? "OK" : "Failed?");
}
}
And it worked. I don't think this is your real problem. Probably it's in another part of your code.

Dividing error in java language

I have a simple java program that does not operate the way that I think it should.
public class Divisor
{
public static void main(String[] args)
{
int answer = 5 / 2;
System.out.println(answer);
}
}
Why is this not printing out 2.5?
5 / 2 is integer division (you're even storing it in an integer variable), if you want it to be 2.5, you need to use floating point division:
double answer = 5.0 / 2.0;
Integer division is always going to be equal to normal mathematical division rounded down to the nearest integer.
Java has integer division which says: integer divided by integer results in integer. 2.5 cannot be represented with integer so the result is floored to 2.0. Moreover, you store the result in integer.
If you need floating point division you can cast one of operands to double and change answer type to double as well. You use literal values here, so changing 5 to 5. makes this literal value double.
In the end the following should work for you:
double answer = 5. / 2;
Note, you don't even need a zero sign after a dot symbol!

Java float not acting correctly [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does (360 / 24) / 60 = 0 … in Java
I am having this problem:
float rate= (115/100);
When I do:
System.out.println(rate);
It gives me 1.0
What... is the problem?
115 and 100 are both integers, so will return an integer.
Try doing this:
float rate = (115f / 100f);
You're performing integer division (which provides an integer result) and then storing it in a float.
You need to use at least one float in the operation for the result to be the proper type:
float rate = 115f / 100;
float rate= (115/100);
Does the following things:
1) Performs integer division of 115 over 100 this yields the value 1.
2) Cast the result from step 1) to a float. This yields the value 1.0
What you want is this:
float rate = 115.0/100;
Or more generally, you want to convert one of the pieces of your division into a float whether that is via casting (float)115/100 or by appending a decimal point to one of the two pieces or by doing this float rate = 115f / 100 is completely up to you and yields the same result.
In order to perform floating-point arithmetic with integers you need to cast at least one of the operands to a float.
Example:
int a = 115;
int b = 100;
float rate = ((float)a)/b;
use float rate= (float)(115.0/100); instead
It is enough to put float rate = 115f / 100;
The problem you have is that your dividend and divisor are declared as integer type.
In mathematic when you divide two integer results only with remainder. And that is what you assign to your rate variable.
So to have the result as you expected, a remainder with fraction (rational numbers). Your dividend or divisor must be declared in a type with precision.
Base two known types with precision are float (Floating point) and double (Double precision).
By default all numbers (integer literals for purists) written in Java code are in type int (Integer). To change that you need to tell the compiler that a number you want to declare should be represent in different type. To do that you need to append a suffix to integer literal.
Literals for decimal types:
float - f or F; 110f;
double - d or D 110D;
Note that when you would like to use the double, type you can also declare it by adding a decimal separator to literal:
double d = 2.;
or
double d = 2.0;
I encourage you to use double type instead of float. Double type is more suitable for most of modern application. Usage of float may cause unexpected results, because of accuracy problem that in single point calculation have bigger impact on result. Good reading about this “What Every Computer Scientist Should Know About Floating-Point Arithmetic”.
In addition on current CPU architecture both float and double have same performance characteristic. So there is not need to sacrifice the accuracy.
A final note about floating point types in is that non of them should be use when we write a financial application. To have valid results in this matter, you should always used [BigDecimal]

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);

Beginners Java Question (int, float)

int cinema,dvd,pc,total;
double fractionCinema, fractionOther;
fractionCinema=(cinema/total)*100; //percent cinema
So when I run code to display fractionCinema, it just gives me zeros. If I change all the ints to doubles, then it gives me what Im looking for. However, I use cinema, pc, and total elsewhere and they have to be displayed as ints, not decimals. What do I do?
When you divide two ints (eg, 2 / 3), Java performs an integer division, and truncates the decimal portion.
Therefore, 2 / 3 == 0.
You need to force Java to perform a double division by casting either operand to a double.
For example:
fractionCinema = (cinema / (double)total) * 100;
Try this instead:
int cinema, total;
int fractionCinema;
fractionCinema = cinema*100 / total; //percent cinema
For example, if cinema/(double)total is 0.5, then fractionCinema would be 50. And no floating-point operations are required; all of the math is done using integer arithmetic.
Addendum
As pointed out by #user949300, the code above rounds down to the nearest integer. To round the result "properly", use this:
fractionCinema = (cinema*100 + 50) / total; //percent cinema
When you divide two ints, Java will do integer division, and the fractional part will be truncated.
You can either explicitly cast one of the arguments to a double via cinema/(double) total or implicitly using an operation such as cinema*1.0/total
As some people have already stated, Java will automatically cut off any fractional parts when doing division of integers. Just change the variables from int to double.

Categories