1

I want to know the result of a String with many math operations. An example:

((49 -(16 - 72))/(21+ (72/(81 + 57))))

I'm using eval function and it works, but the result of a divide operation has to be an integer, and I don't know how to do it! Any idea?

devnull
  • 118,548
  • 33
  • 236
  • 227
Daniel 976034
  • 189
  • 1
  • 1
  • 18

1 Answers1

3

Simply use parseInt:

parseInt((49 -(16 - 72))/(21+ parseInt(72/(81 + 57))))

Or use the bitwise or with 0 as the second argument:

((49 -(16 - 72))/(21+ (72/(81 + 57))|0))|0

In the future Math.trunc should be the preferred method.

TimWolla
  • 31,849
  • 8
  • 63
  • 96
  • Yep, that code parses the final solution. I have to floor EVERY divide operation. I just wonder if there's some option to do this. For example, (72/(81 + 57)) = 0 – Daniel 976034 Mar 24 '14 at 01:14
  • @Daniel976034 Append a `|0` to every division. There is currently no other way. – TimWolla Mar 24 '14 at 01:15
  • Please, can you type an example? I don't understand you. – Daniel 976034 Mar 24 '14 at 01:17
  • @Daniel976034 I edited my answer. But as an short example: `(1/2|0) === 0` – TimWolla Mar 24 '14 at 01:19
  • Thank you very much @TimWolla. But remember that it's a string :P – Daniel 976034 Mar 24 '14 at 01:22
  • @Daniel976034 What exactly do you mean? – TimWolla Mar 24 '14 at 01:26
  • Don't worry! I did it! What I asked you is about how I could add parseInt when there's a divide operation! but I realize it's a string!! so I can do a replace of each "(" by "parseInt" and it works! var texto = s.toString().replace(/\(/g, 'parseInt('); – Daniel 976034 Mar 24 '14 at 01:35
  • @Daniel976034—that means you're calling *parseInt* far more often than you need to, the only other way would be to parse the string and insert it only where needed (which might be more trouble than it's worth if the current method gets you by). Note that the equation can be written `'(49 -(16 - 72))/(21+ 72/(81 + 57))'`, in which case there is no bracket before `72` to use to insert *parseInt*. – RobG Mar 24 '14 at 01:45
  • @RobG Yep, I know it, perhaps a good regex is better, but it's just for a gymkhana. – Daniel 976034 Mar 24 '14 at 10:29
  • @Daniel976034—OK, as long as you can guarantee the input format and someone doesn't decide to remove the redundancy. :-) – RobG Mar 25 '14 at 03:17
  • hehehe no, the redundancy won't be removed. It's a rule! Thank for your time @RobG – Daniel 976034 Mar 25 '14 at 15:34