1

Possible Duplicate:
Is there a function to round a float in C or do I need to write my own?
Rounding Number to 2 Decimal Places in C

I am looking for a function in c which could round my float variable to another float variable with two digits after the decimal point, help and demonstrate please. thank you

Update: I need this function for calculation purpose, not for printing.

Community
  • 1
  • 1
daNullSet
  • 669
  • 2
  • 6
  • 16
  • 1
    Out of curiosity, is this just for printing out to the console? Or for some calculation? – Cornstalks Nov 23 '12 at 03:20
  • 2
    See http://stackoverflow.com/questions/497018/is-there-a-function-to-round-a-float-in-c-or-do-i-need-to-write-my-own. Note particularly that floats do not exactly correspond to decimals; if you care that much about the representation internally, you probably want a proper fixed-precision decimal. – isturdy Nov 23 '12 at 03:26
  • 2
    Or just store values in cents rather than dollars (pounds, euros etc). – John Carter Nov 23 '12 at 03:27
  • You also want to read this: http://stackoverflow.com/a/273383/8331 – John Carter Nov 23 '12 at 03:36
  • 1
    If, as @therefromhere suspects, you are storing money values as floats, stop doing that. You are asking for sorrow. – Andy Lester Nov 23 '12 at 03:59

1 Answers1

4

you may try something like this:

float a = 1.234568;
float b = ((int) a*100.f) / 100.f;

instead of (int) you may use floor()/ceil() according to your requirements.

lenik
  • 23,228
  • 4
  • 34
  • 43
  • I am new to programming, I am getting everything except: what 100.f is supposed to do? – daNullSet Nov 23 '12 at 03:32
  • `100.f` is floating point number 100.0, if you write just 100.0 it will be considered a `double` and you might get type conversion warnings. – lenik Nov 23 '12 at 03:34