How Close is Javascript Math.Round for C # Math.Round?

I know, after reading the https://stackoverflow.com/a/166168/ which will be examined on your number, decide if the midpoint is an even or odd number, and then will return an even number. The example number was 2.5, which was rounded to 3. I tried my own little experiments to find out what would happen, but I still need to find some specifications about this, or even if it is agreed between browsers.

Here is an example JavaScript snippet using jQuery to render:

$(document).ready(function() { $("#answer").html(showRounding()); }); function showRounding() { var answer = Math.round(2.5); return answer; } 

This returns a '3'.

I would like to know the following: how close is rounding in JavaScript to the C # equivalent? The reason I do this is because I would like to use a JavaScript method that uses Math.Round and rewrite the same method in C # and would like to know that after rounding the number I get the same results.

+7
javascript c # rounding
source share
2 answers

Here's the full javascript spec for Math.round(x) :

15.8.2.15 round (x) Returns the Number value that is closest to x and equal to a mathematical integer. If two integer values โ€‹โ€‹of Number are equal to close to x, then the result will be a Value close to + โˆž. If x is already an integer, the result is x.

  • If x is NaN, the result is NaN.
  • If x is +0, the result is +0.
  • If x is -0, the result is -0.
  • If x is + โˆž, the result is + โˆž.
  • If x is -โˆž, the result is -โˆž.
  • If x is greater than 0 but less than 0.5, the result is +0.
  • If x is less than 0 but greater than or equal to -0.5, the result is -0.

NOTE 1 Math.round (3.5) returns 4, but Math.round (-3.5) returns -3.

NOTE 2: The value of Math.round (x) is the same as the value of Math.floor (x + 0.5), except when x is -0 or less than 0, but greater than or equal to -0.5; for these cases, Math.round (x) returns -0, but Math.floor (x + 0.5) returns +0.

The C # language specification does not provide any specific rounding algorithm. The closest we have is the documentation for .NET Math.Round . From this you can see that some of the javascript cases are not applied ( Math.Round processes only decimals and doubles, not infinity), and method overloads give you more control over the result - you can specify the number of fractional digits in the result and the rounding method midpoint. By default, Math.Round uses "rounding bankers" (to even).

+5
source share

Rounding ECMAScript is mostly naively asymmetric rounding (with added +-Infinity ). WRT portes your JavaScript code to C #, you are probably better off avoiding .NET Math.Round (since it is always symmetrical ) and use Math.Floor instead:

 double d = -3.5d; double rounded = Math.Floor(d + 0.5); // -3 matches JavaScript Math.round 

That is, if you need strict emulation of ECMAScript Math.Round .

+2
source share

All Articles