This question already has answers here:
Floating point arithmetic not producing exact results [duplicate]
(7 answers)
Closed 9 years ago.
Here is the extracted code :
long timeMs = 1473;
double timeS = (timeMs / 1000) + (timeMs% 1000) / 1000.0;
System.out.println(timeS);
And the output is:
1.4729999999999999
So basically, I was just trying to convert the time taken in seconds into milliseconds.
After I saw this I thought my method is wrong, so I've tried other inputs, such as 1472, 1474, 1173, 3 etc which all gave the correct values(1.472, 1.474, 1.173, 0.003).
I think I've came across something similar to this a while ago in a book called Java Puzzlers, but have forgotten. Can anyone tell me why this is happening (and a proper term/error)?
Thanks.
Use this instead, but it's because of IEEE 754 rounding rules.
double timeS = (timeMs / 1000.0); //+ ((double) (timeMs % 1000) / 1000.0);
Use BigDecimal for more accurate rounding and scaling.
long timeMs = 1473;
double timeS = (timeMs / 1000d);
BigDecimal usefulName = new BigDecimal(timeS).setScale(3, RoundingMode.HALF_UP);
System.out.println(usefulName);
Related
This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 1 year ago.
I am writing a function in which it should return the total amount that has been rounded to the nearest up pound (£). Note: the inputs are written as whole numbers without decimal places so 260 is actually £2.60 etc.
E.g.
intput: 260 -> output: 0.40
intput: 520 -> output: 0.80
total = 1.20 (because 40p + 80p)
I have written out this function:
public Double nearestPoundTotaler(List<Integer> transactions)
{
double total = 0.00;
for(Integer amount : transactions)
{
int penceAmount = amount % 100;
int penceToNearestNextPound = 100 - penceAmount;
double answer = penceToNearestNextPound / 100.0;
total = total + answer;
}
return total;
}
I have written unit tests and the logic works but the test fails since the decimal places are incorrect. E.g. if passing 260,260,260 into the method, I get the following:
expected: 1.2
but was: 1.2000000000000002
I've tried numerous ways of removing the decimal place but I haven't seemed to find a way. Also is it possible to perform this logic with the .round() methods in Java?
With the primitive type double you can't express exact numbers, due to numerical issues. Try using BigDecimal instead and the .divide() method. There you can also set the scale to 2 (2 decimal places) and the RoundingMode (usually HALF_UP)
This question already has answers here:
Retain precision with double in Java
(24 answers)
Is floating point math broken?
(31 answers)
Closed 4 years ago.
Eclipse gives the wrong result when trying to calculate the sum of two floats.
In my code, there are 2 float variables: float from = 0.025 and float to = 1.
Then result has double variable: double value = 7 * from / to.
Eclipse compiler shows: value = 0.174999997019767760
In excel calculator, this result was value = 0.175
How can I solve this an issue?
This is simply due to your Java program not rounding the result the same way the excel calculator does. This is a result of the way computers handle floating point arithmetic. You have two options: round the result, or use the java BigDecimal class. If you want to round the result, you can use:
float from = 0.025f;
float to = 1;
double value = 7 * from / to;
DecimalFormat ds = new DecimalFormat("#.###");
double rounded = Double.parseDouble(ds.format(value));
System.out.println(rounded);
If you would rather not have to round, you can use the BigDecimal class.
Java BigDecimal
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
I doing a simple calculation from 2 variable and I got in to an issue...
In fact when I try to do " double d = 1000 (which is the first var) / 3600 (which is the 2nd var); it result in a 0. So why ? Any hint about that ?
1000 and 3600 are ints, so when you do 1000 / 3600 you get 0. Then, you are assigning double d to this result of zero. You can instead write 1000.0/3600.0 or if these two numbers are variables, you can cast them to doubles first.
This question already has answers here:
Why does the division of two integers return 0.0 in Java? [duplicate]
(6 answers)
Closed 9 years ago.
The following is my code that works ::
public class AvgSpeed{
public static void main(String[] args){
double kph, km, hours, seconds, minutes, time;
km = (1.6 * 24);
hours = 1;
minutes = 2/3f;
seconds = 35/3600f;
time = hours + minutes + seconds;
kph = km/time;
System.out.println(kph);
}
}
If I remove the f's for minutes and seconds, it keeps printing out 38.4, which is not right. It should be some number close to 22.906
I don't even know the reason why I need to add the f, I did it on a whim. I thought declaring the two variables as a double was enough?
Declaring the variables as doubles doesn't make 2 or 3 a double. The conversion to double only happens after 2/3 is computed in integer arithmetic. To fix this, do the calculation in double arithmetic:
minutes = 2.0/3;
// ^ double
seconds = 35.0/3600;
// ^ double
The trailing f you appended made 3f and 3600f float literals. That's close to what you want, but not as good as doubles.
In Java, 18.45 is a double data type which holds 64-bit. float data type can hold up to 32-bit only. Adding the extra f makes it a float (float literal).
See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for more detail
double minutes;
minutes = 2/3;
This code takes two integers, divides them, converts the result to a double and stores it in minutes. In that order. To get the result you want you need to convert to doubles before the division happens. You managed to do this by adding f (use d for double, btw). You could also do it with minutes = 2.0/3.0;
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java Integer Division, How do you produce a double?
double wang = 3 / 2;
Log.v("TEST", "Wang: " + Double.toString(wang));
Logcat output...
07-04 09:01:03.908: VERBOSE/TEST(28432): Wang: 1.0
I'm sure there's an obvious answer to this and probably I'm just tired from coding all night but this has me stumped.
In many languages, Java being one of them, the way you write a number in an expression decides what type it gets. In Java, a few of the common number types behave like this1:
// In these cases the specs are obviously redundant, since all values will be
// cast correctly anyway, but it was the easiest way to show how to get to the
// different data types :P
int i = 1;
long l = 1L;
float f = 1.0f; // I believe the f and d for float and double are optional, but
double d = 1.0d; // I wouldn't bet on what the default is if they're omitted...
Thus, when you declare 3 / 2, you're really saying (the integer 3) / (the integer 2). Java performs the division, and finds the result to be 1 (i.e. the integer 1...) since that's the result of dividing 3 and 2 as integers. Finally, the integer 1 is cast to the double 1.0d which is stored in your variable.
To work around this, you should (as many others have suggested) instead calculate the quotient of
(the double 3) / (the double 2)
or, in Java syntax,
double wang = 3.0 / 2.0;
1 Source: The Java Tutorial from Oracle
Integer division of 3 by 2 is equal to 1 with residue of 1. Casting to double gives 1.0
3 and 2 are integer constants and therefore 3 / 2 is an integer division which results in 1 which is then cast into a double. You want 3.0 / 2.0
Try: double wang = 3.0 / 2.0;
That's the expected behaviour. "3" and "2" are both int values, and when you perform 3 / 2 the result will also be an int value which gets rounded down to 1. if you cast both to double before you perform the division then you'll get the result that you expect:
double wang = (double)3 / (double)2;