2

I've been playing with Script#, and I was wondering how the C# numbers were converted to Javascript. I wrote this little bit of code

int a = 3 / 2;

and looked at the relevant bit of compiled Javascript:

var $0=3/2;

In C#, the result of 3 / 2 assigned to an int is 1, but in Javascript, which only has one number type, is 1.5.

Because of this disparity between the C# and Javascript behaviour, and since the compiled code doesn't seem to compensate for it, should I assume that my numeric calculations written in C# might behave incorrectly when compiled to Javascript?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Peter Olson
  • 139,199
  • 49
  • 202
  • 242

1 Answers1

4

Should I assume that my numeric calculations written in C# might behave incorrectly when compiled to Javascript?

Yes.

Like you said, "the compiled code doesn't seem to compensate for it" - though for the case you mention where a was declared as an int it would be easy enough to compensate by using var $0 = Math.floor(3/2);. But if you don't control how the "compiler" works you're in a pickle. (You could correct the JavaScript manually, but you'd have to do that every time you regenerated it. Yuck.)

Note also that you are likely to have problems with decimal numbers too due to the way JavaScript represents decimal places. Most people are surprised the first time they find out that JavaScript will tell you that 0.4 * 3 works out to be 1.2000000000000002. For more details see one of the many other questions on this issue, e.g., How to deal with floating point number precision in JavaScript?. (Actually I think C# handles decimals the same way, so maybe this issue won't be such a surprise. Still, it can be a trap for new players...)

Community
  • 1
  • 1
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • 1
    All numbers in JavaScript are effectively doubles in C# (there is no int/float/long/decimal equivalent). This includes the math operators, as noted (all operators are effectively done on doubles). I think both are defined to work in accordance with [IEEE754-binary64/FP64 (or "double")](http://en.wikipedia.org/wiki/Double-precision_floating-point_format) (although slight differences across architectures may appear in edge cases: consider x86 has an 80bit internal FPU). –  Dec 01 '11 at 04:53
  • @pst - Thanks for the extra info. I started typing that last paragraph before I remembered how C# handles decimals, but then I figured I'd leave it in my answer since an awful lot of JavaScript programmers are not aware of this behaviour (hence the final, parenthetical statement). – nnnnnn Dec 01 '11 at 05:03