Rounding to nearest whole number [duplicate] - java

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)

Related

How to round a number to a user given number of decimal places [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 3 years ago.
What I'm trying to do is take the user given input (operand) and round my current number to the amount of decimals that the operand is. For example if my current number in the calculator program this is running on is 15.44876, and the user input is 2, I would like the returned value to be 15.45, or just 15.44 at least.
public double round(double operand){
this.answer = Math.round(this.answer, operand);
return this.answer;
I know the code above is incorrect, but it's just a place holder since I'm pretty confused on this.
You can multiply by the appropriate power of 10, round, and then divide by the same power of 10. This approach assumes that the numbers are in ranges such that overflow will not be a problem.
public double round(double value, int places) {
final double scale = Math.pow(10.0, places);
return Math.round(value * scale) / scale;
}
If overflow might be an issue, there are other approaches.

How to prevent number being rounded to 0, Android Studio [duplicate]

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 6 years ago.
public int total;
public int likes;
public double average;
total = 5;
likes = 21;
average = likes / total;
Log.d("Average", average);
Hi, average = likes / total should return 4.2, however, its running 4.0. How can I keep it as 4.2 and not 4.0?
Calculations using only integers causes the end result to be integer, even if later you assign it to a floating point value like double. Integer division works by counting how many times the denominator can fit entirely in the numerator.
To resolve, you have to cast at least one of the 2 operands in the division so that the division is performed already in double precision (numbers inside arithmetic operations are automatically casted to a type that allow greater precision than its operands, if at least one of the operands have that precision):
average = (double)likes / total;
or
average = likes / (double) total;
Please note that this is different than average = (double) (likes / total);, which would cast the result after it has already been rounded down.
average = (double)likes / total;

Rounding price to the nearest multiple of 5cent in java

I'm new to java programming. I would like to round up a price to the nearest 2 decimal places.
E.g.
38.82 into 38.80
38.87 into 38.90
38.85 stays the same.
I did the E.g. 1 and E.g. 2 but it comes out only 1 decimal place. E.g. 38.82 to 38.8
this is my code:
import java.text.DecimalFormat;
public class RoundUp {
public static void main(String[] args){
DecimalFormat df = new DecimalFormat("#.##");
double num = 38.84;
System.out.println(df.format(Math.round(num*10.00)/10.00));
}
}
I have looked into other model answers by experts in this web but none of it really answer my question. Setting into 2 decimal places, I'm using DemicalFormat. That I know, but rounding the number, let's say 38.83 to 38.85 and 38.87 to 38.90 is what I really want. It is a rounding system that my country is using. Can check it out here.
And please everybody.. please don't change my question to a duplicate one. you think that its a duplicated one, please ask me for more info. I can ensure you that it is not a duplicated (I think...)
One way to do this is to convert the price to cents, divide by 5, round to, multiply by 5 again and convert back to dollars:
double rounded = Math.round(num * 100.0 / 5.0) * 5.0 / 100.0;
When you deal with money, you should avoid using float or double variables and use an integer datatype instead in order to avoid problems due to the fact that calculations with float or double values are not exact.
You could use the following solution (when dealing with int):
public static int roundUp(int cents) {
int centsMod5 = cents%5;
if (centsMod5 > 0) {
cents += (5 - centsMod5);
}
return cents;
}

How to make any double datatype into 0.00 (2 digits after decimal point) format taking in another double datatype (Android/Java)? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
I'm beginner in android developing. How can I make a double datatype i.e 56.32534 into 56.33? But I want to take it in a double variable. I know a way but it takes in String.
Double value = 56.32534;
DecimalFormat df = new DecimalFormat("0.##");
String newvalue = df.format(value);
Here, newvalueis a string. But I want to take it in a double datatype.
I need to use it's numeric value not just in display purpose only.
You can use Math.round():
double value = 56.32534;
double rounded = Math.round(100 * value) / 100.0;
The multiplication and then division by 100 is necessary because Math.round() rounds to the nearest long value.
If you want to generalize this to a variable number of digits, you can use something like this:
public double round(double value, int digits) {
double scale = Math.pow(10, digits);
return Math.round(value * scale) / scale;
}
This will even work if digits is not positive; it will round to the nearest integer if digits is 0, to the nearest 10 if digits is -1, to the nearest 100 if digits is -2, etc.
We need a little bit more precision on what you want to do. Do you want to display it that way or just use its numerical value that way ?
If it's the display your solution is ok. You could always get back the float number from the string afterwards.
On the other hand if you want to use it as a numerical value what you could do is
double rounded = (double) Math.round(myfloat * 100) /100;
I think it works. Can't test it as I'm on my mobile though

Why do I need to add an 'f' to value so my code outputs the right value? [duplicate]

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;

Categories