# functions for rounding and truncatin

What are the functions for rounding and truncatin a float number?
What headers have to be included?
Thanks.

• : What are the functions for rounding and truncatin a float number?
: What headers have to be included?
: Thanks.
:
[blue]
Hi,

One could do the above by using [b]simple type casting[/b].

Note that [b]type casting[/b] 'truncates a number, not rounds.

For example:

[code]
#include
using namespace std;

int main()
{
// Declaring the variable
double v = 1234.56789;

// Casting the double to an int
int n = int(v);

cout << "v = " << v << " , n = " << n << endl;

return 0;
}
[/code]

The program should return [code]v = 1234.57, n = 1234[/code]

The double value 1234.57 is converted to an integer value 1234.
[/blue]
• : : What are the functions for rounding and truncatin a float number?
: : What headers have to be included?
: : Thanks.
: :
: [blue]
: Hi,
:
: One could do the above by using [b]simple type casting[/b].
:
: Note that [b]type casting[/b] 'truncates a number, not rounds.
:
: For example:
:
: [code]
: #include
: using namespace std;
:
: int main()
: {
: // Declaring the variable
: double v = 1234.56789;
:
: // Casting the double to an int
: int n = int(v);
:
: cout << "v = " << v << " , n = " << n << endl;
:
: return 0;
: }
: [/code]
:
: The program should return [code]v = 1234.57, n = 1234[/code]
:
: The double value 1234.57 is converted to an integer value 1234.
: [/blue]
:

You can also round floats to the nearest whole number (up or down) with a small amount of code
[CODE]
float a = 5.7f;
float r = (long)((a)+0.5);
printf("%f
", r);
[/CODE]
That would print "6.000000"
If a = 5.3f then it would print "5.000000"
Or you could use printf("%ld
", r); and it would print "6" or "5"
• Thank you. That really worked and solved part of my problem. But what if I need to round the number keeping two decimal digits, for example, from 1.5492 to 1.55?
• [b][red]This message was edited by DB1 at 2002-10-14 14:23:44[/red][/b][hr]
: Thank you. That really worked and solved part of my problem. But what if I need to round the number keeping two decimal digits, for example, from 1.5492 to 1.55?
:
Well, you need to do a bit of math. One way is to step through the number and round as you go..
[CODE]
float a = 1.5492f;
printf("a: %f
", a);
float b = a - (long)a;
float c = b*1000.0f;
float d = (long)((c)+0.5f);
float e = d/10.0f;
float f = (long)((e)+0.5f);
float g = f/100.0f;
float h = g + (a-b);
printf("h: %f
", h);
[/CODE]

The easy way is to just use precision..
[CODE]
float a = 1.5492f;
printf("a: %.2f
", a);
[/CODE]