Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript float compared to C# float

just simple question about JS/C# floats. I am making multiplayer game and normally have to synchronize stuff between client and server. Now the question, are C# floats and Javascript floats same data type? Like, can I send one to another and it will understand each other. I will send floats with scientific notations because I think this way it will be the shortest and most precise. Unless you guys have any other ideas :)

Thanks in advance.

like image 411
Vili Volcini Avatar asked Oct 18 '25 01:10

Vili Volcini


1 Answers

A C# double and a JavaScript Number are the same thing, both are double-precision (64-bit) IEEE-754 binary floating point numbers ("binary64"). (A C# float is just single-precision [32-bit, "binary32"], so if you want the same thing JavaScript has, use double, not float.)


Side note: Although they're the same number type, their respective "to string" operations are slightly different. For instance, given the number 0.87090686143883822 (which is really 0.8709068614388382201241256552748382091522216796875, the nearest value IEEE-754 binary64 can hold), the "to string" operation from C#, JavaScript, and Java (which also uses binary64 for its double) are:

0.870906861438838   - C#'s ToString()
0.87090686143883822 - C#'s ToString("R")
0.8709068614388382  - JavaScript's toString()
0.8709068614388382  - Java's String.valueOf(double)

I don't know the rules for C#, but JavaScript and Java both default to including only as many digits as are required to distinguish the number from its nearest representable neighbor. C#'s ToString() doesn't do that (0.870906861438838 converts to 0.870906861438838, precisely, losing the remaining 0.0000000000000002201241256552748382091522216796875). C#'s ToString("R") includes an unnecessary additional digit.

like image 186
T.J. Crowder Avatar answered Oct 19 '25 14:10

T.J. Crowder