What does 100% accurate mean? To determine accuracy, you must also determine the precision. For example, if I divide 100 by 3 and state that the answer must be precise to the nearest integer (perhaps because my processor only supports this level of precision) then the answer is 33 and that’s 100% accurate.

However, if I specify my precision to 3dp, then the answer is 33.333 (again, 100% accurate).

A decimal type in C# has a precision of 28-29 significant figures (http://msdn.microsoft.com/en-us/library/364x0z75.aspx). The “actual” answer for 100/3 is 33 and an infinite number of 3’s after the decimal point. The decimal type will truncate this to 25-26 3’s. That’s not the actual answer, it’s an answer that’s 100% accurate to 25-26 decimal places.

So…

Go ahead and use doubles (ie floating point numbers) and convert to decimal at the end. Just don’t try comparing variables of type double with each other or you’ll enter a world of pain.

]]>There are an infinite number of ways to represent numbers in binary format. Among these, an infinite number of them allow a number exactly equal to .1 to be represented. And, an infinite number fail to exactly represent .1. The standard format for floating point numbers in binary fails to represent .1, but not because it’s binary.

An object in computer memory, such as a .NET Decimal, will also fail to accurately represent some numbers, even if they are decimal–if not because its format explicitly limits the number of digits it can represent, as with a Float, then because it’s stored in a physical device, and to represent some numbers it would need more memory than the device possessed. Such a number, whose exact representation in some given decimal format would occupy many gigabytes, is unlikely to arise in banking… but it does exist.

Also, decimal numbers are not “our real-world numbering system”. The fact that humans happen to have ten fingers doesn’t magically make one numbering system more real than others.

You’re talking about a few specific, practical matters in a way that makes them sound mathematically universal.

]]>Eric – nice! NP.

]]>Keith – a while back I was thinking about how to do this; at first, I thought just to make a wrapper class around all the possible data types, but your link has a simpler solution (in the comment on Aug 26,16:21). Thanks for the link. 🙂

]]>Answer to this question here

]]>I have a set of classes where I need to compile them to use float, double or decimals depending on the target. Any ideas on how to easily swap all float references for doubles for example to compile two different targets?

Using something like “class MYNumber : Double” so that it is only necessary to change one line of code does not work as Double is sealed, and obviously there is no #define in C#, so I am at a loss on how to do this apparently simple task!

Thanks.

]]>