Jump to content

Basic Math Calculation - Round


Recommended Posts

1 hour ago, slyfox said:

I was under the impression that this formula can be included into "Arg and Var" utility somehow to do the calculation inside the workflow.

 

No. You can construct the calculation, but you can't evaluate it (using Alfred's own calculation engine) within the workflow. Arg and Vars only supports expanding {query} and {var:...} macros.

 

I don't know exactly what @GuiB's workflow in the other thread was doing, but I suspect it was assembling the formula in the Arg and Vars and then passing it back to Alfred for evaluation with tell application id "com.runningwithcrayons.Alfred" to search "{query}" (or similar).

 

1 hour ago, slyfox said:

Or this is only possible with a script?

 

That's a fairly simple and powerful way, yes, but bash is a very poor language for doing maths in.

 

You're better off with a programming language designed for that sort of thing. Here's the correct way to round numbers in Python:

from __future__ import print_function
from decimal import *
import sys

num = Decimal(sys.argv[1])
# Divide by 10 (or whatever)
result = num / Decimal(10)

ctx = getcontext()
# Number of decimal places to round to
ctx.prec = 2
# Rounding mode
# https://docs.python.org/2.7/library/decimal.html#decimal.Context
ctx.rounding = ROUND_HALF_EVEN

print(result, end='')
# Or to round to nearest whole number
# print(result.to_integral_value(), end='')

 

Link to post

@slyfox, yes @deanishe is right about the first example whose passing the Arg & Vars to Alfred, but my second example uses Python.

 

Here is the workflow updated again: https://d.pr/f/z8i7VM

 

But to put it here in the forum:

 

My first one uses an expression in the Arg & Vars (ex: `round(({query}+({query}/0.971))*100)/100` ) and pass it to Alfred using `tell application id "com.runningwithcrayons.Alfred" to search "={query}"`

 

My second example uses a Script Filter set to the Python language and what is great is that you can see directly see the output. You can just change the expression at `val = round(query+(query/0.971),2)` to use what you want.

 

Here is the script:

 

import sys, json

query = float(sys.argv[1])

val = round(query+(query/0.971),2)

data = {'items': [{
    'title': val,
    'subtitle': str(query)+'+('+str(query)+'/0.971)',
	'arg': val,
    'text' : {
        'copy' : val,
        'largetype' : val
    },
}]}

sys.stdout.write(json.dumps(data))

 

Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...