469,623 Members | 1,545 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,623 developers. It's quick & easy.

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
6 posts views Thread by ng_mr | last post: by
5 posts views Thread by shapper | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.