Is there a way to floor/ceil based on whether the value is over 0.5 or under?

为君一笑 提交于 2019-12-07 12:43:26

问题


I am trying to round my values so that if it's 0.5 or greater, it becomes 1, else it becomes 0. For example:

3.7 -> 4;
1.3 -> 1;
2.5 -> 3;
...

Any ideas?


回答1:


Math.Round(3.7,MidpointRounding.AwayFromZero);

http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx

In the above, I made use of AwayFromZero for rounding because the default is Banker's rounding, so if the fraction is 0.5, it is rounded to nearest even. So 3.5 becomes 4 (nearest even), but 2.5 becomes 2 (nearest even). So you choose a different method as shown above to make 3.5 to 4 and 2.5 to 3.




回答2:


The simplest way is add 0.5 to the input, then cast to int.




回答3:


I arrived last, so I'll tell something different. You round 0.5 to 1 by not using double! Use decimals. double aren't good to have "exact" numbers.

Launch this piece of code and have fun (note that there is/was a "bug" in mono on numbers like 0.49999999999999994, so to run it on ideone I had to modify it a little to try to round 1.5: http://ideone.com/57XAYV)

public static void Main()
{
    double d = 1.0;
    d -= 0.3;
    d -= 0.2;

    Console.WriteLine("Standard formatting: {0}", d); // 0.5
    Console.WriteLine("Internal Representation: {0:r}", d); // 0.49999999999999994
    Console.WriteLine("Console WriteLine 0 decimals: {0:0}", d); // 1
    Console.WriteLine("0 decimals Math.Round: {0}", Math.Round(d, MidpointRounding.AwayFromZero)); // 0
    Console.WriteLine("15 decimals then 0 decimals Math.Round: {0}", Math.Round(Math.Round(d, 15, MidpointRounding.AwayFromZero), MidpointRounding.AwayFromZero)); // 1
}


来源:https://stackoverflow.com/questions/7864404/is-there-a-way-to-floor-ceil-based-on-whether-the-value-is-over-0-5-or-under

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!