This is the most common difficulty with Code Quest problems. Unless explicitly stated otherwise, all problems use a "half away from zero" method of rounding. Particularly if you're in the United States, this is likely the method you learned in school. You may wish to write your own function to handle rounding. Most programming languages use a different method by default, which is likely to result in wrong answers. Numbers with a decimal portion with an absolute value greater than or equal to .5 will round away from zero, those with an absolute value less than .5 will round toward zero. For example, when rounding to one decimal point:
1.46 rounds away from zero to 1.5
1.45 rounds away from zero to 1.5
1.44 rounds toward zero to 1.4
-1.44 rounds toward zero to -1.4
-1.45 rounds away from zero to -1.5
-1.46 rounds away from zero to -1.5
It is tricky to round a decimal number (double) to a certain number of decimal places. The algorithm is surprisingly long and must account for negative numbers. Here is an example of how to round to one decimal place:
public static double round(double number) {
double powerOfTen = 10;
double exp = number * powerOfTen;
double remainder = Math.abs(exp) - Math.floor(Math.abs(exp));
if (remainder >= 0.5) {
if (exp > 0.0) {
exp += 1.0;
} else {
exp -= 1.0;
}
}
return ((int)exp)/powerOfTen;
}
Go to the 2021 Lockheed Martin Programming Competition problem #9, "Where's My Change." Note that your code must produce the right results for both input files: Sample.in.txt and Official.in.txt. Please compare your output files to the given ones to see if your code is correct.
Here is an example of how to round a decimal number to the nearest 1000:
value = Math.round(value/1000)*1000;
Practice With Formatted Output
Do the Confusing Conversions problem from the 2021 Lockheed Martin packet.