English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Hey, i was hoping someone could help me with rounding floats in C programming language to the closes 10 (ex: 12 > 10, 16 > 20, 26 > 30) and also to two decimal places (ex: 1.2359453 > 1.24, 23,33999 > 23.34)

2007-11-28 08:46:05 · 2 answers · asked by Anonymous in Science & Mathematics Mathematics

2 answers

In the second case, do you still want the numbers stored as floats or do you simply want to display the floats with appropriate rounding? If it is simply a display issue, then sprintf is your friend and you can simply format the number to have two decimals. The rounding will be automatic.

But if you want to actually modify the value (be careful what you really want to do here!), then you would be better off converting to fixed point notation, in which you use an integer to represent the numerals and keep track of the decimal point yourself.

The following applies to both of your cases.

I define a rounding macro:
#define ROUND(x) ( (x) >= 0.0 ) ? (int)((x)+0.5) : (int)((x)-0.5)

Note that two cases have to be handled - positive and negative rounding.

Let's take your first two examples 12 and 16. I would first scale by dividing by 10 to place the decimal point where I need it for the macro to work. Then I would apply the macro.
ROUND(1.2) would return 1 and ROUND(1.6) would return 2.
You would then take this result and scale back to the original magnitude by multiplying by 10.

For your example 1.2359453, scale first by multiplying by 100. Apply the macro. ROUND(123.59453) = 124. Now scale back to the orignal magnitude by dividing by 100.

See how it works?

Let's do one negative one to demonstrate what happens there (you can, of course change the macro if you want the rounding to behave differently)

Round -0.049355 to the fourth position past the decimal.

Scale the number by multiplying by 10000, resulting in -493.55. Invoke the ROUND macro.
ROUND(-493.55) will subtract 0.5 because the number is negative resulting in -494.05, which it then truncates to -494. Take the result and scale back to the original magnitude by dividing by 10000, resulting in -0.049400

2007-11-28 09:14:07 · answer #1 · answered by dogsafire 7 · 0 0

Most programming languages will have an 'int' function which just returns the integer part of a decimal number.
I.e. int(5.6) = 5 or int (3.14) = 3
Now to get int to round to the nearest whole number you just need to do int(x + 0.5)

To round to nearest tens do this: 10 * int(0.1*x + 0.5)
To round to 2 decimal places: 0.01 * int(100*x + 0.5)
And so on for any amount of decimal places or power of ten.

2007-11-28 08:54:46 · answer #2 · answered by Ian 6 · 0 0

fedest.com, questions and answers