Implement method that returns the result of division int num1 by int num2 in the special format.
Example1: num1 = 12345678, num2 = 10000: the result should be “1,234.5678”.
Example2: num1 = 10000000, num2 = 10000: the result should be “1,000.0000”.
Solution in Java
import java.text.DecimalFormat;
...
public String formattedDivision(int num1, int num2) {
if (num2 == 0) {
throw new ArithmeticException("Division By Zero");
}
double result = (double) num1 / num2;
DecimalFormat df = new DecimalFormat("###,###.0000");
String str = df.format(result);
if (str.startsWith(".")) return "0" + str;
return str;
}
Another solution in Java
public String formattedDivision(int num1, int num2) {
int intResult = num1 / num2;
double dResult = (double) num1 / num2;
String result = "" + intResult;
String formatted = "";
for (int i = 0; i < result.length(); i++) {
formatted = formatted + result.substring(i, i+1);
if (i != result.length() - 1 && (result.length() - 1 - i)%3 == 0) {
formatted = formatted + ",";
}
}
int afterDot = (int) Math.round((dResult - num1/num2) * 10000);
return formatted + "." + (afterDot == 0 ? "0000" : afterDot + "");
}