四舍五入一个浮点数 [英] round off a float number

查看:83
本文介绍了四舍五入一个浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想四舍五入,例如.如果我的值是8.25,则自动将其舍入为8.5,如果值是8.75,则应将其变为9

Hi,
I want to round off a number like for eg. if my value is 8.25 then automatically it be rounded up to 8.5 and if value is 8.75 then it should become 9

推荐答案

您没有任何内置函数想要
使用Math.round函数
There is not any in-built function as you want
use Math.round function
float tmp = 7.26;
float help = (float) Math.Round(tmp, 1);



并尝试根据您的要求使用条件创建函数.



and try to create your function using condition as per your requirement.


检查此代码

Check this code

double f =8.25;
            double dresult;

            double dDecim = f - (int)f;
            if (dDecim > 0.5)
                dresult = Math.Round(f, 0);
            else
                dresult = Math.Round(f, 1);


我不认为您真的需要四舍五入.它很少需要并且可能很危险.这是典型的情况.
您很可能需要将数字的四舍五入的字符串表示形式显示在UI中,而这是完全不同的事情,实际上经常需要这样做.
因此,您需要使用
I don''t think you really need rounding. It is rarely needed and can be dangerous. This is a typical situation.
Much more likely that you need a rounded string presentation of a number to show in UI, and this is completely different thing, which is really needed very often.

So, you need to use
string.Format<code> with appropriate format string.<br />
See:<br />
<a href="http://msdn.microsoft.com/en-us/library/system.string.format.aspx">http://msdn.microsoft.com/en-us/library/system.string.format.aspx</a>[<a href="http://msdn.microsoft.com/en-us/library/system.string.format.aspx" target="_blank" title="New Window">^</a>],<br />
<a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx">http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx</a>[<a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx" target="_blank" title="New Window">^</a>],<br />
<a href="http://msdn.microsoft.com/en-us/library/0c899ak8.aspx">http://msdn.microsoft.com/en-us/library/0c899ak8.aspx</a>[<a href="http://msdn.microsoft.com/en-us/library/0c899ak8.aspx" target="_blank" title="New Window">^</a>].<br />
<br />
<dd>—SA</dd>


这篇关于四舍五入一个浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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