5

Why does this result in 0 and not 1?

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

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

Acorn
  • 49,061
  • 27
  • 133
  • 172
  • are you sure you aren't applying something else to this. my tests resulted in 1 being the result of this calculation. – Paul Farry Feb 28 '12 at 02:42

3 Answers3

8

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Is it possible to round a number to the nearest whole number consistently rounding up for `.5`? – Acorn Feb 28 '12 at 02:29
  • Yes, use the Microsoft product, or file a bug report on Mono :-) – paxdiablo Feb 28 '12 at 02:51
  • The former isn't an option as I'm writing code for the Unity3d framework which uses Mono, but if it's indeed a bug, I'll try and pester someone about it :) – Acorn Feb 28 '12 at 02:53
  • @Acorn, a cursory search of the bug DB turned up nothing. You can file a report at http://www.mono-project.com/Support – paxdiablo Feb 28 '12 at 02:55
0

0.5 is a double.

If you do

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

It will work as expected

Keith
  • 1,119
  • 2
  • 12
  • 23
0

This also returns 1.0 for me when I debugged it.

Math.Round(0.5, 0, MidpointRounding.AwayFromZero)
Seany84
  • 5,526
  • 5
  • 42
  • 67