This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to round a number to n decimal places in Java
When multiplying two numbers in java happens this:
double a = 9.495 * 100;
Expected result:
a = 949.5;
But the obtained result is:
a = 949.4999999999999
When I try to round number 9.495 in two decimal places the result is 9.49 instead of 9.50
Any ideas how to solve this problem?
If you want accurate floating point computations, do not use the float or double types, but rather make use of the BigDecimal class.
This is a side effect of floating point calculations, and is well understood, but not necessarily intuitive. This question has actually been asked literally thousands of times, and you need to study how floating point arithmetic works.
To get around this, if you only need 2-decimal precision, then use a integer instead.
For example, if you're dealing with currency, and you want to buy a 100 items for $4.95, then you represent the cost of that value as the integer "495", an multiply that by 100, which gives you "49500". You always treat the last two digits as cents, so "49500" is $495.00.
You cannot. Floating point and double precision numbers in a computer cannot represent all possible values.
Related
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 8 years ago.
How do I round a float number if it returns a whole value? And, how do I round if it's like:
5/2 = 2.5
and NOT like this:
5/2 = 2.50000000
A double does not allow you to specify the number of decimal places it has; you may be able to set as many as you wish to 0, but they are still there. (Note that, mathematically, the two values you show for 5/2 are the same.) What you can do is control how many get displayed; since you haven't specified how you are attempting to display this value, I can't help in how to modify it to limit the number of decimal places to show.
Whenever needed, you can make some modifications on your double, such as using the setRoundingMode method of DecimalFormat class, along with the RoundingMode enum.
As mentioned before though, 2.5 is the same with 2.500000 in a double, you do not have to change its digits.
I guess you are trying to print your double and you get a number of unwanted digits in the output. In that case, I suggest though that you convert your double into a formatted string and use it as such:
System.out.println(String.format("%.2f", myDouble));
You are a bit confused I think...
2.5 and 2.50000000 are the exact same thing!
They are just written differently.
I don't really understand what you are trying to achieve but you can round floats like this:
float result = Math.round(someFloat);
If you always want to round up or down regardless of what the number is use:
float result = (float)Math.ceil(someFloat);
or
float result = (float)Math.floor(someFloat);
This question already has answers here:
Why can't decimal numbers be represented exactly in binary?
(22 answers)
Floating point arithmetic not producing exact results [duplicate]
(7 answers)
Closed 9 years ago.
I'm simply trying to calculate percentage_imp, but instead of 0.22 (exactly 0.22, no rounding error), I get 0.22000000000000003!!
I used to get similar odd results, and I've been told to move from float to double, but this one is still odd!
All the variables below are double!
double percentage_imp= budget - (sum_minlessi)/ (sum_i + sum_lessi);
Thats because of the floating point precision values.
You must read:- What Every Computer Scientist Should Know About Floating-Point Arithmetic
You must also read how floating point arithmetic and its internal representation works.
0.22 is not representable as a double.
As an example, 1/3 cannot be represented in base-10, so we approximate with 0.3333333333333333.
Its a rounding error inherit in binary calculations. Not all rational decimal numbers can be represented as a single decimal number in binary. As such, when you perform operations such as multiply and divide, you'll get some nasty error on the last few digits.
Moving from double to float doesn't change this as double is simply a double precision floating point number.
I suggest you look at this link
As a extra bonus in java, simple operations such as binary multiplications are optimized as much as possible utilizing any sort of hardware optimizations when possible yielding different answers on different machines. If you require consistent behavior across all machines use the strictfp keyword in your class declaration.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Moving decimal places over in a double
Why is the following sum of numbers not equal to 0.4622? but 0.46219999999999994
Double total = new Double(0.08) + new Double(0.0491) + new Double(0.3218) +
new Double(0.0113) + new Double(0.0); // = 0.46219999999999994
I have an application that checks the users input.
The user inputs 5 decimal numbers and a total number. The application checks if the sum of all 5 numbers capped at 4 decimals behind the komma is equal to the total number.
Capping it gives me 0.4621 which is not equal to 0.4622. I can't use DecimalFormat because it rounds it up. And if i explicitly say, round down then it will fail for this situation.
Any suggestion for how I can solve this?
Try with java.math.BigDecimal. Double rounds result. You will just have to use add method, not + operator.
Avoid using float and double if exact answers are required-- Item 48 -- Effective Java Second edition
Use BigDecimal instead.
Looks like a classic case of floating point arithmetic. If you want exact calculations, use java.math.BigDecimal. Have a look at What Every Computer Scientist Should Know About Floating-Point Arithmetic
When you use floating point arithmetic you must also use appropriate rounding.
BTW: Don't use an object when a primitive will do.
double total = 0.08 + 0.0491 + 0.3218 + 0.0113 + 0.0;
System.out.printf("%.4f%n", total);
double rounded = Math.round(total * 1e4) / 1e4;
if (rounded == 0.4622)
System.out.println("rounded matched");
prints
0.4622
rounded matched
as expected.
Double and float in Java are internally represented as binary fractions and can therefore be not precise in representing decimal fractions (IEEE standard 754). If your decimal number calculations require precision, use Java.math.BigDecimal.
Floating point representation is a close approximation so you will have these little rounding errors when you use float and double. If you try to convert 0.08 to binary for instance you will realize that you cannot actually do it exactly. You need to consider this whenever you use double and float in calculations.
0.0810 = 0.00010100011110101110...2
a repeating pattern. So no matter how many bits you use this will have a rounding error.
That is yet another rounding issue. You should never compare doubles and expect them to be exactly equal. Instead define a small epsylon and expect the result to be within epsylon of the expected answer.
Any floating point value is inexact. The solution is to use DecimalFormat when you have to display the values. And no, it doesn't round up but to the nearest value.
From the javadoc :
DecimalFormat uses half-even rounding (see ROUND_HALF_EVEN) for
formatting.
The internal representation of floating point numbers like Double is never a exact one. This is why during calculations such errors can occur.
It is always suggested to format such a result to a specific number of digits past the comma, so you result would be correctly be display as "0.4622" with 4 to 15 or more digits.
Perhaps checking the string input directly would be more feasible for you. That is check the length of characters after the decimal place.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Double calculation producing odd result
I'm writing a program in Java that deals with a lot of double arithmetic. I eventually get to the point where I need to add 0.6666666666666666 and -0.666666666666667. However, the answer that I get is -3.3306690738754696E-16.
In other words,
double d1 = 0.6666666666666666;
double d2 = -0.666666666666667;
System.out.println(d1 + d2);
prints out "-3.3306690738754696E-16". Why is this happening?
Thank you in advance.
doubles are not perfectly accurate, and not every decimal can be perfectly represented as a double (see this). For all practical purposes, -3.3306690738754696E-16 is 0 *. However, if you need more precision, use BigDecimal. Keep in mind that this alternative will not be nearly as efficient as using primitive doubles. It's up to you to decide if you need this level of accuracy and to make a choice accordingly.
*: Evidently, that number is not exactly zero, but for the majority of real-world calculations and computations, a value that small would be inconsiderable. In meters, this value is smaller than the diameter of protons and neutrons - i.e. very very small. That's what I mean by "for all practical purposes".
double values cannot represent all values precisely and this is such an example. You can use BigDecimal instead:
BigDecimal bd1 = new BigDecimal("0.6666666666666666");
BigDecimal bd2 = new BigDecimal("-0.666666666666667");
System.out.println(bd1.add(bd2));
Output:
-4E-16
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 7 years ago.
This seems like a very simple error:
double quarter = 1/4;
Is giving
0.0
Anybody know why this might be happening?
I am trying to store pretty much all the fractions from 1/2 to 1/20 (Just the ones with 1 on the top and in int on the bottom), so I won't be able to input the decimal straight away for all of them.
I've read and heard that floating-point datatypes are not a good way of storing fractions, so is there any other way (in Java)?
Try:
double quarter = 1d/4d;
The division of two integers gives a truncated integer. By putting the d behind the numbers you are casting them to doubles.
For starters, you're trying to divide 1/4 as integer values, and it's truncating it. 1. / 4 will correctly give you 0.25; other ways to express the number 1 as a double include 1d, 1.0, and so on.
Other approaches include:
Use BigDecimal to store values to an exact decimal precision. (For example, this is the preferred way to deal with monetary values.)
Use a Fraction or Rational class, either rolling your own or using one from a library. Apache Commons has Fraction and BigFraction, though their documentation seems a little sketchy.
Java is performing integer division because your denominator is an integer.
Try the following:
double quarter = 1 / 4.0;
Or:
double quarter = 1 / (double) 4;
The reason you're getting 0.0 is because the division is done as an integer division and then the result is converted to float. Try this, for example: double quarter = 1.0/4.0; - you should get (pretty much) the expected result.
However, depending on your requirements, this may not be the best way to deal with the problem. For example, you can't store 1/3 in a decimal. The perfect way would be to store simple fraction as a pair of integers. You can create a class for it (with some arithmetic methods) or start by using a simple array. It all depends on your needs.