0

I got into a small confusion of numerical calculation.

in C#:

> 44.5 + (((5220886 / 2) - 2496118) / 897211) * 9
< 44.5

in JS:

> 44.5 + (((5220886 / 2) - 2496118) / 897211) * 9
< 45.646803817608124

Which one is correct? Can anyone help me to understand why this is happening?

P.S: Though there is one post in SO which is dealing with C# floats, my question is a little bit different as I am not doing anything with strings. This is pure numerical calculations.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Jeya Suriya Muthumari
  • 1,947
  • 3
  • 25
  • 47
  • 8
    C# has integers, JavaScript does not. The whole right part in C# is integer math. – Dmitry Mar 06 '19 at 07:17
  • 2
    That should be the correct answer, not how floats work. There’s a big difference in the calculation due to data types. Please add an answer, @Dmitry – Sami Kuhmonen Mar 06 '19 at 07:18
  • 2
    add `.0` at the end of numbers in C# to do floating point division instead of integer division – Slai Mar 06 '19 at 07:21
  • 1
    Add a `d` after any of the divisors in the C# expression to force all operands to be evaluated as doubles, and see what happens. – Ian Kemp Mar 06 '19 at 07:27
  • and related : https://stackoverflow.com/questions/22820057/basic-maths-c-sharp-not-working – xdtTransform Mar 06 '19 at 07:32

2 Answers2

3

C# has integers, JavaScript does not. The whole right part in C# is integer math, which means that the fractions got truncated. In C# you need to add .0 (e.g. var x = 2.0;, var is now a double) to the number to make it into a double while in JavaScript all numbers are internally represented as doubles.

Dmitry
  • 6,716
  • 14
  • 37
  • 39
1

In C# when using an integer divisor, the result is rounded towards zero.

Since JavaScript does not have the same types as C#, floating point division is used instead. To have the same result in C#, add a 'd' or a '.0' to the divisor.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Markus Dresch
  • 5,290
  • 3
  • 20
  • 40