Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 0.5 rounded with MidpointRounding.AwayFromZero result in 0?

Why does this result in 0 and not 1?

Math.Round(0.5, 0, MidpointRounding.AwayFromZero)

Here's an example: http://ideone.com/ayMVO

like image 258
Acorn Avatar asked Feb 28 '12 02:02

Acorn


1 Answers

Normally, with issues like that, it's because the number cannot be represented exactly in IEEE754 - it's most likely it's being converted to 0.4999999999... or something like that which would round to zero.

However, 0.5 (1/2) is exactly representable in IEEE754 so that's not the case here.

It's possible that the compiler made a mistake in converting the text to a number but I would think that unlikely. In fact, when I compile and run the following in VC#2010:

using System;
namespace ConsoleApplication1 {
    class Program {
        static void Main (string[] args) {
            Console.WriteLine (Math.Round (0.5, 0, MidpointRounding.AwayFromZero));
        }
    }
}

I get the output of 1 as expected.

So I don't think your question is quite complete. Now it may be that your actual situation doesn't use a hard-coded value of 0.5 but instead uses a variable which you believe to be 0.5.

My answer to that would be that, while it may be close to 0.5 (certainly close enough that a simple WriteLine of it might output 0.5), it's probably a touch below 0.5, which would cause my comments in the first paragraph above to once again kick in.


Based on your link, it appears that Mono 2.8 may have a bug. I'd suggesting seeking support from the developers (or just raising a bug report) here.

Actually, having tried it locally with gmcs 2.6.7, it's definitely a bug. That exact code compiled okay but generates 0 rather than 1. A bug report has been raised, and I've added my own information to it.

like image 80
paxdiablo Avatar answered Sep 29 '22 00:09

paxdiablo