一个“四舍六入五成双”规则的实数取位代码。
时间:2010-04-10 来源:gzstyxb
BOOL SetFloatDecimal(float input, int dec, float &out)
{
out = 0.0;
if (0 != _isnan(input)
|| dec < 0
|| dec > 15)
return FALSE;
#define BUFFERSIZE 100
char buffer[BUFFERSIZE] = {0};
const char point[] = ".";
int size = sprintf(buffer, "%.20f", input);
int index = strcspn(buffer, point);
if (0 >= index)
{
out = input;
return TRUE;
}
if ((BUFFERSIZE - 1) < index)
return FALSE;
BOOL bAdd = FALSE;
index = index + dec + 1;
if ('5' < buffer[index])
{
bAdd = TRUE;
}
else if ('5' == buffer[index])
{
if (0 != buffer[index - 1] % 2)
{
bAdd = TRUE;
}
}
buffer[index] = '\0';
sscanf(buffer, "%f", &out);
if (bAdd)
out += 1 / pow(10, dec);
return (0 == _isnan(out));
}
相关阅读 更多 +