看了大佬的文章https://rationmcu.com/clang/2416.html
引申了一下保留一位小数的方法。
浮点数四舍五入取一位小数:
//四舍五入取一位小数
float CImplicitSurface::Get1fromfloat(const float& val)
{
float temp1 = val;
int t1 = (uint32_t)(temp1 * 100) % 10;
if (t1 > 4)
{
temp1 = (float)((uint32_t)(temp1 * 10.0f) + 1) / 10.0;
}
else
{
temp1 = (float)((uint32_t)(temp1 * 10.0f)) / 10.0;
}
return temp1;
}
浮点数四舍五入取2位小数:
float CImplicitSurface::Get1fromfloat(const float& val)
{
float temp1 = val;
int t1 = (uint32_t)(temp1 * 1000) % 100%10;
if (t1 > 4)
{
temp1 = (float)((uint32_t)(temp1 * 100.0f) + 1) / 100.0;
}
else
{
temp1 = (float)((uint32_t)(temp1 * 100.0f)) / 100.0;
}
return temp1;
}
浮点数四舍五入取整:
int CImplicitSurface::Get1fromfloat(const float& val)
{
float temp1 = val;
int t1 = (uint32_t)(temp1 * 10) %10;
if (t1 > 4)
{
temp1 = (float)(uint32_t)(temp1 + 1) ;
}
else
{
temp1 = (float)((uint32_t)(temp1)) ;
}
return (int)temp1;
}