how to enforce the evaluation type of an expression to be double

236 Views Asked by At

how could I make sure that the expression is always evaluated as a double even if it has no double in it, I came across this website https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types, It says :

check the relevant part from here so how can I override this problem and make sure that the expression is always evaluated as a double,

I am trying to use the library of Flee, and whenever I put a fraction in it like(4/3) it deals with it as an integer, not even a float, this ruins the whole calculation so I have to get around this problem,

If I try and use the following expression it works

(4.0/3) or (4/3.0) = 1.33333 the faulty case is as follows (4/3) = 1 hopefully my explanation is clear

3

There are 3 best solutions below

1
emagers On

As mentioned in the docs, that is a feature of the language. You can always cast either the numerator or the denominator into a float or double which will end with a result of the same type:

int a = 4;
int b = 3;
double result = (double)a / b;
1
Hervé On

Solution 1

Use the double annotation which tells to the compiler that the number is actually a double

4d / 3

(d for double, also works for float using f)

Solution 2

Use explicit casting

(double)4 / 3
0
yy uu On

I managed to solve the problem by forcing Flee Library to not consider any given input as Integer anymore, I did that by writing the following code:

ExpressionContext context = new ExpressionContext();
context.Options.IntegersAsDoubles = true;

Best of luck to you all