## Floating Point Rounding

### January 8, 2013

This question appears regularly at beginning-programmer discussion sites:

Write a function that takes a floating point number

fand an integernand rounds the floating point number tonplaces after the decimal point. For instance, given the floating point number 1000/7, rounding to 3 places would produce 142.857, rounding to 2 places would produce 142.86, rounding to 1 place would produce 142.9, and rounding to 0 places would produce 143. For extra credit, allownto be negative, indicating roundingbeforethe decimal point; for instance, rounding 1000/7 to -1 places would produce 140.

It’s not fair to use a built-in `round`

function if your language provides one.

Your task is to write the function described above. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

My Java solution here.

a C solution

a Scheme solution

I guess I should check the suggested solution to see if it is essentially the same as mine before posting mine. ^_^

[…] Pages: 1 2 […]

> javabloggi said

>January 8, 2013 at 10:52 AM

>

>My Java solution here.

Your solution does not perform rounding correctly. You seem to be checking the digit in one more significant place value than you need to be in order to determine if rounding up is needed.

For example, from your output:

01 Enter numbers:

02 1000/7,3

03 Answer: 142.858

However, the correct answer should be 12.857.

Here’s my java solution:

public class FPR {

public static double round(double f, int n) {

double div = Math.pow(10, (double) n);

if (div*f*10 % 10 >= 5) {

return ((double) ((int) (div*f)) + 1)/div;

} else {

return ((double) ((int) (div*f)))/div;

}

}

public static void main(String[] args) {

for (int i = 3; i >= -2; i–) {

System.out.println(“1000/7,” + i + “: ” + round(1000.0/7.0, i));

}

}

}

Thanks.

Katzby

>However, the correct answer should be 12.857.

Sorry, I meant to say it should be 142.857.

Thanks.

Katzby

An overly complicated python version =)

>However, the correct answer should be 12.857.

>Sorry, I meant to say it should be 142.857.

>Thanks.

>Katzby

Thanks for letting me know. I corrected the mistake.

Every answer posted so far handles negative values incorrectly. Also, it doesn’t appear anyone implemented an unbiased tie-breaking scheme?

This solution handles both issues correctly (tie-breaking done with round-to-even) as well as the extra credit.

However, it doesn’t support the technical definition of significant digits.

oops typo on line 11. should be: