java - Issue rounding a double with math.round() -
this question has answer here:
- round double 2 decimal places [duplicate] 13 answers
i have java exercise need write method takes 3 parameters; 2 doubles, , 1 char in specific order. once have them need return double value rounded 2 decimal places using math.round(). depending on rules shown.
im not sure how can go getting double value down 2 decimal places, appreciated. thankyou!
import java.util.scanner; public class questionfour { public static void main(string[] args){ scanner scan = new scanner(system.in); system.out.println("enter double number"); double num1 = scan.nextdouble(); system.out.println("enter double number"); double num2 = scan.nextdouble(); system.out.println("enter 1 of +, -, *, /, %"); char c = scan.next().charat(0); system.out.println("the value of calculation is: " + docalculation(num1, num2, c)); } public static double docalculation(double num1, double num2, char c){ double result = 0; if(c == '+'){ return result = num1 + num2; } else if(c == '-'){ if(num1 > num2){ return result = num1 - num2; } else if(num1 < num2){ return result = num2 - num1; } } else if(c == '*'){ return result = num1 * num2; } else if(c == '/'){ if(num2 == 0){ return 0; } else{ return result = num1 / num2; } } else if(c == '%'){ return result = num1 % num2; } else{ system.out.println("error! enter 1 of +, -, *, /, %"); } return math.round((result * 100)/100); } }
try this. replace
system.out.println("the value of calculation is: " + docalculation(num1, num2, c));
to
system.out.println("the value of calculation is: " + string.format( "%.2f", docalculation(num1, num2, c)));
wiki
Comments
Post a Comment