2
function Round2DecimalPlaces(l_amt) {
    var l_dblRounded = +(Math.round(l_amt + "e+2") + "e-2");
    return l_dblRounded;
}

Fiddle: http://jsfiddle.net/1jf3ut3v/

I'm mainly confused on how Math.round works with "e+2" and how addition the "+" sign to the beginning of Math.round makes any difference at all.

I understand the basic of the function; the decimal gets moved n places to the right (as specified by e+2), rounded with this new integer, and then moved back. However, I'm not sure what 'e' is doing in this situation.

aaronk6
  • 2,345
  • 1
  • 16
  • 24
Smak
  • 95
  • 12
  • Guys before downvoting explain the reason!!!This is a pretty good question – cssGEEK Mar 03 '15 at 19:26
  • 4
    `e+2` is a string, therefore your `l_amt` becomes a string. `Math.round('4.2' + 'e+2')` -> `Math.Round(4.2e+2)`. basically it's taking your number, stringifying it as a scientific-notation "float", rounding, then undoing the scientification. It's basically a very very ugly way of saying `round(number * 100) / 100`. – Marc B Mar 03 '15 at 19:27
  • Essentially what's happening is the argument to the function (`l_amt`) is being multiplied by 100 (that's the effect of the `e+2`). Then that string is passed to `Math.round()` which will convert its argument to a number and either round it to the next highest or lowest integer. Then THAT result is *divided* by 100 (`e-2`). The `+` in front of the whole thing coerces the final result to a number. – mbcrute Mar 03 '15 at 19:36
  • 1
    This is horrible code, do not use! It won't work with very small or very large values, is rather slow, and contains an unknown number of other oddities. Demonstration: `Round2DecimalPlaces(0.3-0.2-0.1)`. You expected `0`? Hah! – Bergi Mar 03 '15 at 19:53
  • Thanks for the answer Marc B. Wish you had posted it as an answer and not a comment so I could give you a check mark! – Smak Mar 03 '15 at 19:53

2 Answers2

2

eX is a valid part of a Number literal and means *10^X, just like in scientific notation:

> 1e1 // 1 * Math.pow(10, 1)
10

> 1e2 // 1 * Math.pow(10, 2)
100

And because of that, converting a string containing such a character sequence results in a valid number:

> var x = 2;
> Number(x + "e1")
20
> Number(x + "e2")
200

For more information, have a look at the MDN JavaScript Guide.

But of course the way this notation is used in your example is horrible. Converting values back and forth to numbers and strings is already bad enough, but it also makes it more difficult to understand.

Simple multiple or divide by a multiple of 10.

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
1

The single plus operator coerces a the string into a float. (See also: Single plus operator in javascript )

Community
  • 1
  • 1
omdel
  • 871
  • 9
  • 13