Die PHP-Funktion ist nicht von mir, ich habe sie aus diesem Forum: Thread in externem Forum [Rechnen mit Strings]
Ich habe sie nach AHK übersetzt und sogar überarbeitet, sodass sie auch (hoffentlich) nach dem Punkt-vor-Strich-System arbeitet:
Code: Select all
StrCalc(str){ ;http://www.php.de/php-tipps-2010/66855-mathematische-berechnung-vom-stringinhalt.html#post507927
stack := Object()
v := Object()
m := Object()
v[0] := v[1] := op := ""
pos := 0
str := RegExReplace(RegExReplace(str, "\s"), "\d+[*/]\d+", "($0)")
while(pos := RegExMatch(str, "([()+*/^-]|(\-?\d+))", regex, pos + (StrLen(regex1) ? StrLen(regex1) : 1)))
m.Insert(regex1)
for i, tk in m
{
if(tk = "+" OR tk = "-" OR tk = "*" OR tk = "/" OR tk = "^"){
op := tk
continue
}
else if(tk = "("){
stack.Insert([v[0], v[1], op])
v[0] := v[1] := op := ""
continue
}
else if(tk = ")"){
kResult := v[0]
v[0] := stack[stack._maxIndex(), 1]
v[1] := stack[stack._maxIndex(), 2]
op := stack[stack._maxIndex(), 3]
stack.Remove()
v[(v[0] = "") ? 0 : 1] := kResult
bracketMode := 1
}
if(!bracketMode)
v[((op = "") && (v[0] = "")) ? 0 : 1] := tk
if(v[1] != ""){
if(op = "^")
v[0] := v[0] ** v[1]
else
v[0] := ((op = "+") * (v[0] + v[1])) + ((op = "*") * (v[0] * v[1])) + ((op = "/") * (v[0] / v[1])) + ((op = "-") * (v[0] - v[1]))
op := v[1] := ""
}
bracketMode := 0
}
return v[0]
}
Das habe ich jetzt des Öfteren getestet, ich garantiere allerdings keine Richtigkeit der Ergebnisse.
Ein Aufruf sieht zum Beispiel so aus:
Code: Select all
MsgBox, % StrCalc("10 + 20") ;30, die Leerzeichen werden ignoriert
MsgBox, % StrCalc("10^3") ;1000
MsgBox, % StrCalc("20+30*10") ;320, wegen Punkt vor Strich
MsgBox, % StrCalc("(20+30)*10") ;500
- Potenz vor Punkt
- Prozent akzeptieren (z.B. "1000*10%" = 100)
SAPlayer