Using Math.round to round to the nearest tenth? [duplicate] - java

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 9 years ago.
I just wanted to ask a quick question regarding the Math.round method. I'm trying to compute the division of two ints into a double. The equation looks like this: 199/39. When I do this it returns 5.0 as the answer. I know the answer should be 5.1 with some more decimals. I have been told to use the Math.round method to round it to the nearest tenth, but I have no idea how to accomplish this. Should I change that double variable to a int and make it int/int=int? I'm not sure how Math.round even works to get 5.1 as I've read it only rounds to the nearest integer not decimal point. Any help would be fantastic.
P.S This is homework, but I ask only because I can't find any information in my notes, slides, or book on how to use Math.round.

You don't need Math.round() to get a resultant decimal value. If you divide an int by an int, you will get an int. if you want a decimal, then cast double to one of the input values. Then you will get a double as a result.
(double) 199 / 39
199.0 / 39
// both return
5.102564102564102

I know the answer should be 5.1 with some more decimals.
Not with integer division it shouldn't. 5 is correct.
If you want a floating-point answer, you need to provide at least one floating-point operand, e.g. 199/39.0.
You can then format that for printing with as many or few decimal places you like, with System.printf() or DecimalFormat.
You can't round the floating-point value itself to decimal places, because it doesn't have decimal places, it has binary places.
See this question for a full discussion, especially my answer there.

Your specific answer:
roundedNumber = (double)Math.round(unRoundedNumber * 10) / 10;
In general, the equation is:
roundedNumber =
(double)Math.round(unRoundedNumber * Math.pow(10, digitsToRoundTo))
/ Math.pow(10, digitsToRoundTo);

Thanks for all the help. After reading your posts and looking at it some more I ended up doing ratio=((double)199/39) and then going
ratio=(double)Math.round(ratio*10)/10. Doing that got me the 5.1 i was looking for.

Related

How to round a float number in Java if its a whole? [duplicate]

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

Division is incorect in java [duplicate]

This question already has answers here:
Floating point arithmetic not producing exact results [duplicate]
(7 answers)
Closed 9 years ago.
I'am confused. I'm trying to get an int value:
Integer ord = new Double(33 / (-2 * 1.1)).intValue();
Expectation: -15
Output: -14
What's wrong?
When I try:
Double d = 33 / (-2 * 1.1);
Output: -14.999999999999998
Any ideas? Thanks in advance!
.intValue() will trunc the frarctinal part so you can use Math.ceil(), Math.floor() or you can use Math.round() to approximate it to the nearest value
Integer result = (int) Math.round(new Double(33/(-2*1.1))); //-15
Integer result = (int) Math.floor(new Double(33/(-2*1.1))); //-15
Integer result = (int) Math.ceil(new Double(33/(-2*1.1))); //-14
You can see that Math.ceil() give us 14 because this is a negative number -14>-15 so the ceil of -14.9999 is -14 and the inverse apply on Math.floor()
intValue() doesn't do round but truncate.
The double output of -14.999999999999998 has it's origin in the precision of the double type. A floating point number is always a sum of 2^n numbers. The result is that not all numbers can be represented precisely, even with double.
Your integer example returns -14 because the integer value of -14.999999999999998 is -14. There is no rounding when getting the integer value. It is just cut of at the decimal point.
For rounding use either Math.ceil() for rounding up, Math.floor() for rounding down or Math.round() for general rounding.
When getting the int value of a double, java isn't doing any round up or down for you. It just omits the decimals.
What you want to do is to use the Math.round(double) to get the value you are expecting.
I believe the java doc for Math.round() says it will return a long value, but if you are sure that your result never will be larger than the maximum int value, then you can cast it to an int.
int result = (int) Math.round(new Double(33/(-2*1.1)));
Warning: Using the authority argument :P
Josh Bloch has an entire item in his Effective Java book against using double or float when aiming for accuracy. In my life, working with currency, for example, I have had the best results working with BigDecimal
You are using 32 bit float so losing a lot of precision. Try Double d = 33 / (-2 * 1.1d);
And, as everybody say, better round than truncate.

Java sum of all double does not return expected result [duplicate]

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.

Using Java doubles (or anything else) to store simple fractions [duplicate]

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.

Floating point multiplication in java [duplicate]

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.

Categories