10 years, 2 months ago.

Round

How can I get 0.124 as 0.12 or 1.4055 as 1.41 or 5.2 as 5.20? I tried as below but not worked.

  1. include "math.h"

int main(){ x = round(The_Value * 100) / 100; }

1 Answer

10 years, 2 months ago.

Round looks like it should have worked, what result did you get when you tried that?

Here's what comes to mind, generally, based as you did, on scaling the value up, truncating as an integer, then scaling back down (but caution, I didn't compile these to test):

float Round_100th(float x) 
{ 
    return (floor((x+0.005) * 100)/100);
}

float Round_digits(float x, int numdigits)
{ 
    return ceil(x * pow(10,numdigits))/pow(10,numdigits); 
}

float RoundIt(float x)
{
    char buf[10];
    sprintf(buf, "%5.2f", x);
    return atof(buf);
}

You might want to check out "ceil" and "floor" to make sure you get what you want.

Accepted Answer