Rounded floating-point numbers to two decimal places can be done by using various methods.
title: "C++ round double to 2 decimal places."
tags: cpp
canonical_url: https://kodlogs.com/blog/878/c-round-double-to-2-decimal-places
Using the float precision:
int main()
{
float var = 37.66666;
// Directly print the number with .2f precision
printf("%.2f", var);
return 0;
}
Output:
37.67
By using integer typecase:
This method is applied if we are using a function that will tell how to return two decimal point values.
float round(float var)
{
// 37.66666 * 100 =3766.66
// 3766.66 + .5 =3767.16 for rounding off value
// then type cast to int so value is 3767
// then divided by 100 so the value converted into 37.67
float value = (int)(var * 100 + .5);
return (float)value / 100;
}
int main()
{
float var = 37.66666;
cout << round(var);
return 0;
}
Output:
37.67
By using the speintf() and sscanf():
float round(float var)
{
// we use array of chars to store number
// as a string.
char str[40];
// Print in string the value of var
// with two decimal point
sprintf(str, "%.2f", var);
// scan string value in var
sscanf(str, "%f", &var);
return var;
}
int main()
{
float var = 37.66666;
cout << round(var);
return 0;
}
Output:
37.67
Top comments (0)