Using percentage (%) in calculations

Anyone knows, how can I make use of percentages in calculations? Example:

2410%

Percent means “parts of 100” so just replace % with /100

That means, I’ll have to write my own conversion script? Isn’t there anything integrated in Xojo that does this for me, like cdbl or the like?

10% = (10/100) not too complex a conversion

240.1

Yes, but the input I have to deal with is with the %-sign. So what I am trying now ist to convert the string to a calculation:

cdbl(replace(“10%”,"%","/100"))

But that delivers 10 instead of 0.1

Any hints?

It’s simple math.

  1. Convert “10%” to the value 10
  2. Divide that by 100 to get 0.1
  3. There is no step 3

CDbl does not evaluate an expression in the way you want it to. If you want to evaluate an expression expressed in a text you need to look at XojoScript.

Julen

EDIT: There used to be an example showing the use of XojoScript precisely for that purpose in the Example Projects\Advanced\XojoScript folder, look for Evaluator. I say there used to be because the Xojo version I have right now is from 2014.

function percent(pct as string) as double
  dim result as double=val(pct)
  if right(pct,1)="%" then result=result/100
  return result
end function

You might want to have a look at Ben’s MathField

http://www.benandruby.com/bens_software/RBstuff.html

MathField is a free REALBasic EditField class which allows simple math operations to be entered into the EditField and be evaluated. It supports the following operations: +, -, *, /, ^, ( ), {}, [ ] along with negative numbers and nested brackets. This module requires REALbasic 5.5 or higher.

Might need some tweaking … for example do a ReplaceAll with % and /10 … the unit test fails on non-US systems because the unit test is set with a hard-coded decimal separator … you are able to write - - 1 but it evaluates to -1 … but it’s a good first step …

Thanks Dave and Markus. That helps a lot.