Hacker News new | past | comments | ask | show | jobs | submit login

>val total = price + 10.percent * 2

If the price is 10, I would expect total to be 10,2.

(price + 10.percent) * 2 would be 22.

I don't see any way to get 12.






How do you get 10.2? I can only think of two (reasonable) ways to think about this:

    (price + 10.percent) * 2 = (10 + 1) * 2 = 11 * 2 = 22
and

    price + (10.percent * 2) = 10 + 20.percent = 10 + 2 = 12
Personally I would assume the latter, given standard operator precedence, where multiplication precedes addition.

To get the 10.2 you should use the standard tricks to use % in math. For example in a two equations system [1].

  x + y = 100
  90% x + 80% y = 84
you translate it to

  x + y = 100
  90/100 x + 80/100 y = 84
and then you use the Gauss method (or whatever) to solve it.

So in a math class, when you see 20% you translate it to .2, and 10+20% means 10.2. But in a calculator and in the OP project the % button is magic and and 10+20% means 12.

[1] You have to buy two item that in total cost $100, but today there is a 10% discount in one and a 20% discount in the other so you pay only $84. ¿How much is each item?


Percentages are incommensurable with most things, including other percentages in the general case. They are percentages _of something_ and in general the only way you can do addition, subtraction, or comparison is to identify the referent and multiply it out first (the special case is when the other value involved is another percentage with the same referent). So in math class, when you see 20%, you translate it to ".2 _times something_", which is not a value that can be added to 10. You have to figure out what to multiply it by first. In the case of 10+20%, it would be reasonable to assume 20% of 10, which is how you get 12. It would also be reasonable to ask "20% of what?" 10.2 is 10 + 20% of 1, which requires an explanation of how that 1 got involved.

price + (10.percent * 2) looks like 12: If 10.percent = 1, 1*2 = 2. 10 + 2 = 12.

Under the usual rules of operator precedence, that would be the expected answer (multiplication having higher precedence than addition).


How does computer know it's 10% of 10? Unless specified, 10% is 0.1 Or am I an idiot and missing something here

If you oveload "+" to mean whatever-you-want, it's possible. Using bad python [1], it's something like:

  def sum(x,y):
    if is_number(x) and is_number(y):
      return x + y
    elif is_number(x) and is_percent(y):
      return x * (1 + y.value/100)
    else:
      raise fatal_error
I don't claim it's a good idea, but it's possible if the language allows operator overload.

[1] Sorry, my main current language is Racket, but I thought that python-like is easier to read for most people, in spite people that likes python can find like 10 error in 7 LOC.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: