Take the 2-minute tour ×

How to force double x = 3 / 2; to return 1.5 in x without the D suffix or casting? Is there any kind of operator overload that can be done? Or some compiler option?

Amazingly, it's not so simple to add the casting or suffix for the following reason:

Business users need to write and debug their own formulas. Presently C# is getting used like a DSL (domain specific language) in that these users aren't computer science engineers. So all they know is how to edit and create a few types of classes to hold their "business rules" which are generally just math formulas.

But they always assume that double x = 3 / 2; will return x = 1.5 however in C# that returns 1.

A. they always forget this, waste time debugging, call me for support and we fix it. B. they think it's very ugly and hurts the readability of their business rules.

As you know, DSL's need to be more like natural language.

Yes. We are planning to move to Boo and build a DSL based on it but that's down the road.

Is there a simple solution to make double x = 3 / 2; return 1.5 by something external to the class so it's invisible to the users?

Thanks! Wayne

share|improve this question
C# is not a DSL. C# is a general-purpose programming language used to create libraries and applications. If you are allowing non-programmers to write and integrate C# code into your code base, then you have already lost. If you need to provide scripting support, then embed a scripting engine into the application. If you lack for time then create a scaled-down, special-purpose syntax or UI to build these math formulas so you can interpret them how you like in the real code. –  Aaronaught Mar 21 '10 at 4:39
add comment

9 Answers 9

up vote 5 down vote accepted

No, there's no solution that can make 3 / 2 return 1.5.

The only workaround taking into consideration your constraints is to discourage the users to use literals in the formula. Encourage them to use constants. Or, if they really need to use literals, Encourage them to use literals with a decimal point.

share|improve this answer
Well, except for the solutions that do. –  John K Mar 21 '10 at 4:19
@jdk, like? ... –  Anzurio Mar 21 '10 at 4:23
like solution stackoverflow.com/questions/2485881/… .. and like you also mentioned literals but I likely commented after the first sentence or before you were done. So no disagreeance in context after all. –  John K Mar 21 '10 at 4:28
And +1 for reading the question a lot better than I did. –  John K Mar 21 '10 at 4:35
Until we use a DSL, the suggestion of encouraging them to use 3.0 / 2.0 will work. Some users never read manuals. Instead, they just follow example code and the number of users is growing to where it's impossible to personally teach them all. So I will modify all the example code and formulas for them to use 3.0 / 2.0 syntax. That way the new users will automatically imitate that. Plus they're very smart people. So they guess instantly if they remove the .0's and get integer results the reason why. In other words. 3.0 / 2.0 is self explanatory whereas 3D / 2D is definitely not. –  Wayne Mar 21 '10 at 14:15
add comment

never say never... The (double)3/2 solution looks nice...

but it failed for 4+5/6

try this: donated to the public domain to be used freely by SymbolicComputation.com.
It's alpha but you can try it out, I've only run it on a few tests, my site and software should be up soon. It uses Microsoft's Roslyn, it'll put a 'd' after every number if all goes well. Roslyn is alpha too, but it will parse a fair bit of C#.

    public static String AddDSuffixesToEquation(String inEquation)
        SyntaxNode syntaxNode = EquationToSyntaxNode(inEquation);
        List<SyntaxNode> branches = syntaxNode.DescendentNodesAndSelf().ToList();
        List<Int32> numericBranchIndexes = new List<int>();
        List<SyntaxNode> replacements = new List<SyntaxNode>();
        SyntaxNode replacement;
        String lStr;
        Int32 L;
        for (L = 0; L < branches.Count; L++)
            if (branches[L].Kind == SyntaxKind.NumericLiteralExpression)
                lStr = branches[L].ToString() + "d";
                replacement = EquationToSyntaxNode(lStr);

        replacement = EquationToSyntaxNode(inEquation);
        List<SyntaxNode> replaceMeBranches;
        for (L = numericBranchIndexes.Count - 1; L >= 0; L--)
            replaceMeBranches = replacement.DescendentNodesAndSelf().ToList();
            replacement = replacement.ReplaceNode(replaceMeBranches[numericBranchIndexes[L]],replacements[L]);
        return replacement.ToString();


    public static SyntaxNode EquationToSyntaxNode(String inEquation)
        SyntaxTree tree = EquationToSyntaxTree(inEquation);
        return EquationSyntaxTreeToEquationSyntaxNode(tree);

    public static SyntaxTree EquationToSyntaxTree(String inEquation)
        return SyntaxTree.ParseCompilationUnit("using System; class Calc { public static object Eval() { return " + inEquation + "; } }");

    public static SyntaxNode EquationSyntaxTreeToEquationSyntaxNode(SyntaxTree syntaxTree)
        SyntaxNode syntaxNode = syntaxTree.Root.DescendentNodes().First(x => x.Kind == SyntaxKind.ReturnStatement);
        return syntaxNode.ChildNodes().First();
share|improve this answer
add comment

simple, if I'm not mistaken:

double x = 3D / 2D;
share|improve this answer
The questioner says: without the D suffix or casting –  Anzurio Mar 21 '10 at 4:19
add comment

One solution would be writing a method that does this for them and teach them to use it. Your method would always take in doubles and the answer will always have the correct number of decimals.

share|improve this answer
add comment

I'm not pretty sure, but I believe you can get a double using 3.0/2.0 But if you think .0 just as another way of suffixing then it's not the answer too :-)

share|improve this answer
This is a guess, not an answer. Answer questions that are within your expertise. Incorrect answers make it more difficult to find helpful advice. –  Bob Kaufman May 24 '12 at 20:12
add comment

Maybe you can try RPN Expression Parser Class for now or bcParser? These are very small expression parsing libraries.

I like strong, statically typed languages for my own work, but I don't think they're suited for beginners who have no interest in becoming professionals.

So I'd have to say unfortunately your choice of C# might not of been the best for that audience.

Boo seems to be statically typed to. Have you thought about embedding a Javascript engine, Python, or some other dynamically typed engine? These usually are not that hard to plug into an existing application and you have the benefit of lots of existing documentation.

share|improve this answer
Python before version 3.0 has the same problem with division. –  dan04 Mar 21 '10 at 5:33
Well, the users all like c# because their first priority is performance. And critical path code of the system was written in unsafe using pointer so, they say, it's the fastest software in the trading industry. So they put up with C# for now until we can create a full DSL. –  Wayne Mar 22 '10 at 2:13
FYI, as far as language choice, it seems Boo is the answer since it is extensible. That is, you can alter anything in the parser tree at any step in the compile process. My only concern is that the debugger features are vary important and auto code completion that are available with C#. I'm not certain yet what happens to the ability to step through code for business users if it's in a modified-Boo language. –  Wayne Mar 22 '10 at 2:15
add comment

Perhaps an extenstion method on int32?

share|improve this answer
I would LOVE this as a solution and researched it specifically and even tried it. But apparently you cannot create operator over loaders as extension methods according the C# language authors. If I am wrong, please correct me. –  Wayne Mar 22 '10 at 2:10
add comment

Preprocess formulas before passing them to the c# compiler. Do something like:

formula = Regex.Replace(formula, @"(^|[\^\s\+\*\/-])(\d+)(?![DF\.])", "$1$2D")

To convert integer literals to double literals.

Alternately, you could use a simple state machine to track whether or not you're in a string literal or comment rather than blindly replacing, but for simple formulas I think a regex will suffice.

share|improve this answer
Very clever. The "formulas" are really full methods with conditionals and sub methods. It's fairly complex logic on top of the formulas. Specifically, these are automated trading rules. –  Wayne Mar 22 '10 at 2:07
add comment

Try doing it like this:

double result = (double) 3 / 2;

result = 1.5

share|improve this answer
add comment

Your Answer


