469,623 Members | 1,545 Online

# How to round float value?

I have float value, let say 123.456789. How can I round it to two decimal
digits after decimal point?

For example:

123.456789 -> 123.45

It should be some simple way ...

Thanks
Nov 17 '05 #1
2 1408 Steve wrote:
I have float value, let say 123.456789. How can I round it to two decimal
digits after decimal point?

For example:

123.456789 -> 123.45

You should use double, it's more precise:

#include <math.h>
....
double f = 123.456789;
double r1 = floor(f * 100) / 100;
double r2 = floor(f * 100 + 0.5) / 100;

r1 is 123.45, which is 123.456 "floored" to two decimal digits.
r2 is 123.46, which is 123.456 rounded to two decimal digits.

If you really need to work with floats use floorf().
Nov 17 '05 #2
Steve wrote:
I have float value, let say 123.456789. How can I round it to two decimal
digits after decimal point?

For example:

123.456789 -> 123.45

You should use double, it's more precise:

#include <math.h>
....
double f = 123.456789;
double r1 = floor(f * 100) / 100;
double r2 = floor(f * 100 + 0.5) / 100;

r1 is 123.45, which is 123.456 "floored" to two decimal digits.
r2 is 123.46, which is 123.456 rounded to two decimal digits.

If you really need to work with floats use floorf().
Nov 17 '05 #3

### This discussion thread is closed

Replies have been disabled for this discussion.

### Similar topics

 4 posts views Thread by tertius | last post: by reply views Thread by dregier | last post: by 6 posts views Thread by ng_mr | last post: by 7 posts views Thread by ma740988 | last post: by 5 posts views Thread by shapper | last post: by reply views Thread by billypeterson | last post: by reply views Thread by Drake Tucker | last post: by reply views Thread by strativab | last post: by reply views Thread by neerajsundriyal | last post: by reply views Thread by gheharukoh7 | last post: by 2 posts views Thread by JamesNapier | last post: by reply views Thread by aprens | last post: by reply views Thread by isladogs | last post: by 2 posts views Thread by Seth Schrock | last post: by