number rounding - I'm not sure how to round this properly in my Java code -
i'm new java, , i've written code calculates how change need x amount of money payed y priced item. works well; issue whenever there not change owed in hundredths place (ex: $4.60), round down tenths place ($4.6).
if knows how fix this, grateful. have code posted below.
class main { public static void main(string[] args) throws ioexception { scanner scan = new scanner(system.in); double x; double y; double z; system.out.print("enter price of product: $"); x = scan.nextdouble(); system.out.print("enter payed with: $"); y = scan.nextdouble(); z = (int)math.round(100*(y-x)); system.out.print("change owed: $"); system.out.println((z)/100); int q = (int)(z/25); int d = (int)((z%25/10)); int n = (int)((z%25%10/5)); int p = (int)(z%25%10%5); system.out.println("quarters: " + q); system.out.println("dimes: " + d); system.out.println("nickels: " + n); system.out.println("pennies: " + p); } }
edit: thank answered question! ended going decimalformat solve it, , works great.
you can call this:
string.format("%.2f", i);
so in case:
... system.out.print("change owed: $"); system.out.println((string.format("%.2f", z)/100)); ...
string.format()
useful whenever want round significant figures. in case "f" stands float.
Comments
Post a Comment