I write code to test methods, display food and price:
import java.util.Scanner;
public class JavaTutorial5Class {
public static void main(String[] args)
{
greeting("Thunderdome");
prices("Fatburger", 7.50);
}
static void greeting(String restaurant)
{
System.out.println("Welcome to " + restaurant);
}
static void prices(String burger, double price){
System.out.print(burger + " is " + "$" + price);
//System.out.println(Math.ceil(price % 10));
if (Math.ceil(price % 10) == 8.0){
System.out.print("0");
}
}
}
Why is price % 10 == 8.0? And is this really what you have to do to get the tailing 0 on there?
EDIT: All this code is supposed to do is print “Fatburger is $7.50” the problem is that simply giving it the argument 7.50 converts it to 7.5.
In this code, the reason you are getting 8.0 is due to you using
Math.ceil.7.5 % 10is7.5, andMath.ceil(7.5)is8.0.However, and this is something that comes up extremely often and is a very common mistake for beginners… prices should almost never be stored as doubles. Double arithmetic is not always as precise as you would expect, mainly because of how doubles are actually stored. For example, consider this:
You would expect it to output
1.0, but it actually outputs0.9999999999999999The correct way to handle prices is with two
ints: one for dollars, one for cents.