Why casting give me these weird results Java? [duplicate] - java

This question already has answers here:
Why converting from float to double changes the value?
(9 answers)
Closed 2 years ago.
This is the code
public static void main(String[] args) {
double x=5.6556464566546546546556465465465;
float y=(float)x;
double z= 1+y;
System.out.println(x+"\n"+y+"\n"+z);
}
}
and this is the output
5.6556464566546545
5.6556463
6.655646324157715
I can understand the value of x and y but z from where it got those fractional numbers after the 3??!
Thank you very much

Floats are an approximation of the actual number in Java, due to the way they're stored. If you need exact values, use a BigDecimal instead.

Related

Not getting the right answer from celcius to farenheit [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Java explicit type cast for the floating-point division
(2 answers)
Closed 2 years ago.
static void CToF(float c){
float f=32+((9/5)*c);
System.out.printf("%.2f",f);
}
public static void main(String[] args) {
CToF(27);
sc.close();
}
Here the priority of the * and / same so according to their associativity , it will execute from right to left.
So that 9/5 executed first and after that it multiplies with c so the answer is 80.60 but I got 59.00.
What's the problem?
if I make some change and write like this
float f=32+(c*9/5);
it works.xD

How to round float to one decimal point without using DecimalFormat class in java? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 6 years ago.
I was reading my old notes and found a question where a number with two decimal point is converted to a single decimal point. I looked around for answer and couldn't find it. I cannot keep it string as I have to return as a float and compare it.
Math.round was rounding it bad and ceil and floor was giving me error.
I came up with this solution.
public class floatRounding{
public static void main(String[] args){
//System.out.println(temperature((float)32.34));
// System.out.println(temperature((float)32.35));
if (temperature((float)32.34)<temperature((float)32.35)){
System.out.println("Here");
}
}
public static float temperature(float t){
float newt;
//newt=Math.round(t);
String tem=String.format("%.1f",(t+.009));
newt=Float.parseFloat(tem);
System.out.println(newt);
return newt;
}
}
Is there a better solution if I am not using decimal format like in this solution
How to round a number to n decimal places in Java
Thanks in advance. Please forgive if its a dumb question.
You could do something like this:
double x = 1.234;
double y = Math.round(x * 10.0) / 10.0; // => 1.2
System.out.println(y);
This rounds the decimal to the one decimal point, the code is much shorter. Hope this helps, if so accept the answer :)

Java dividing incorrectly [duplicate]

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 7 years ago.
I am using Java 7
I am trying to get a double from dividing two integer:
double chance = 1/main.getConfig().getInt("dailygiftItems.items."+key+".chance");
double w = Math.random();
System.out.println("Pulled: "+main.getConfig().getInt("dailygiftItems.items."+key+".chance"));
System.out.println("itemChance: "+chance);
System.out.println("itemRand: "+w);
if(!(w < chance))continue;
However chance is returning 0. As you can see I have debugged all the values here is what they bring me:
Pulled: 5
itemChance: 0
itemRand: some random double (working correctly)
I was thinking if I did my math wrong and 5/1 is not 0.2 so I used a calculator. However the calculator returned to me 0.2.
I then tested on something simpler testing the same problem:
public class Test
{
public static void main(String[] args)
{
double chance = 1/5;
double w = Math.random();
System.out.println("Chance: "+chance);
System.out.println("Random: "+w);
if(!(w < chance))
{
System.out.println("no");
return;
}
System.out.println("yes");
}
}
This produced the same result as:
Chance: 0
w: some random double (working)
My questions: Why is java not dividing this correctly, and how can I fix it?
Use double chance = 1./main.getConfig().getInt("dailygiftItems.items."+key+".chance");
The . after 1 will force the compiler into considering this is a floating point (double) operation.

Inaccuracy in value inputed [duplicate]

This question already has answers here:
Strange floating-point behaviour in a Java program [duplicate]
(4 answers)
How to resolve a Java Rounding Double issue [duplicate]
(13 answers)
Why is comparing floats inconsistent in Java?
(8 answers)
Closed 8 years ago.
public void Calculate(double value){
int quarter, dime, nickel, remainder;
value *= 100;
System.out.println(value);
This is part of a simple coin counter program (I'm learning programming)--I have value set to 2.26 but found that I didn't get the desired answer, so I did System.out.println(value) to pinpoint where I am not getting the value expected. With value = 2.26, I should get 226 but instead I get 225.99999999999997, which throws off the entire program.
You can add casting to float, then it works fine
public static void main(String[] args) {
Calculate ((float) 2.26);
}
public static void Calculate(float value){
int quarter, dime, nickel, remainder;
value *= 100;
System.out.println(value);
}
Here is the solution
public void Calculate(double value){
int quarter, dime, nickel, remainder;
value *= 100;
System.out.println(round(value,0));
}
You are using double. Double stores many places after decimal in memory so 2.26 is an approximation of a value which is like 2.25999999...
You must round your results to two places of decimal for accurate value.
If you want to know how to round numbers refer to this answer enter link description here

rounding double in java [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 9 years ago.
I have a double valued diagonal matrix stored in a text file.
size(file)~410 Mo
I would like to reduce the size by rounding my double values.
If its a good idea, how to do it in java
0.1706524958886193=>0.17
I need to use this file later in matlab
when i try
dlmread(file) i get out of memory error
If you round the values you are throwing away precision. That may change the results you will get.
A better approach is to store only the diagonal items. There is no point in storing the n^2-n off-diagonal zeroes. Use the diag function to convert a vector into a diagonal matrix. http://www.mathworks.es/es/help/matlab/ref/diag.html
Even more efficient: store the numbers in a binary format instead of text.
Use DecimalFormat class to format the double value to your needs. For example, if you want to keep only 2 digits after decimal point use, "#0.00 and so on. DecimalFormat#format class returns String output which you can use to instantiate Double value.
from
import java.text.DecimalFormat;
public class Tester
{
public static void main(String arg[]) throws Throwable
{
double bigDouble=0.1706524958886193;
DecimalFormat df=new DecimalFormat("#0.00");
String numberString=df.format(bigDouble);
double smallDouble=new Double(numberString);
System.out.println(smallDouble);
}
}
Hope this helps...
Unless I'm misunderstanding the question you can do it like this:
double value = 0.1706524958886193;
value = (double)((int)(value*100))/100; // returns 0.17

Categories