从float中删除最后一位数字 [英] Remove the last digit from float

查看:91
本文介绍了从float中删除最后一位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的浮动值如67,800003,最后一位也可以变化。如何删除最后一位数字,例如数字3?



谢谢

MH

解决方案

这看起来像是一个精确错误我:如果你将67 + 4/5分配给一个浮点变量并打印出来,你就会得到相同的结果!原因是浮点数和双打数在内部转换并存储为二进制数,不能精确地存储像4/5这样的数字,而不是十进制数,你不能准确存储1/3(最好你可以写0.333 ......,用as存储允许的数字。)



根据您用于打印此变量的方法,您可以将输出限制为更少的数字:



  //  使用C风格的printf  
// 小数点后不超过4位数,总共不超过8个字符:
printf( %8.4f \ n,var); // 打印67.8000

// 使用C ++样式cout
// 不超过8个有意义的数字(没有尾随0)
cout<< setprecision( 8 )<< var<< ENDL; // 打印67.8
// 正好6位
cout<< fixed<< setprecision( 6 )<< var<< ENDL; // 打印67.8000





有关使用 cout的更多信息,请参见 setprecision code>操纵者。


  bool  removeLastDigit(float& number)
{
int32_t tempNum = static_cast< int32_t>(number);
tempNum = tempNum% 10 ;
if 0 == tempNum)
返回 false ; // 无要删除的数字
number = number - tempNum;
return true ;
}





虽然不能为实数工作。 :)


正如其他已经说明的那样,float只是一个近似值 - 你不能准确地表示每个数字。在整数部分中使用的位数越多,浮点数的小数部分就越少。当我在用户界面上显示浮点数时,我通常使用%g而不是%f,因为%g会对浮点的小数部分进行舍入,看起来比%。3f或类似的东西更好。

I have a float value like 67,800003 and the last digit can also vary. How can I remove the last digit as in this case digit 3?

Thanks
M.H

解决方案

That looks like a precision error to me: if you assign 67+4/5 to a float variable and print that, you''ll get pretty much the same! The reason is that floats and doubles are internally converted to and stored as binary numbers which cannot accurately store a number like 4/5 anymore than in decimal you cannot accurately store 1/3 (at best you can write 0.333... , with as much digits as your storage allows).

Depending on which method you use for printing this variable, you can limit the output to less digits:

// using C-style printf
// no more than 4 digits after the decimal point, no more than 8 characters total:
printf("%8.4f\n", var); // prints "67.8000"

// using C++ style cout
// no more than 8 meaningful digits (no trailing 0s)
cout << setprecision(8) << var << endl; // prints "67.8"
// exactly 6 digits
cout <<fixed <<setprecision(6) << var << endl; // prints "67.8000"



See setprecision for more info on using cout manipulators.


bool removeLastDigit(float& number)
{
 int32_t tempNum = static_cast<int32_t>(number);
 tempNum = tempNum % 10;
 if( 0 == tempNum )
    return false; //No digit to remove
 number = number - tempNum;
 return true;
}



Won''t work for real number though. :)


As other already stated, float is just an approximation - you can not represent every number accurately. The more digits you use in the integer part, the less precision you have in the fraction part of a float. When I display floating point numbers on user interfaces I usually use "%g" instead of "%f" as "%g" does rounding on the fraction part of the float and looks much nicer than "%.3f" or something similar.


这篇关于从float中删除最后一位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆