-
- 932 Posts
Hi,
I'm calculating a percentage based off of a TV value and I need to shorten the output so that it rounds to the nearest number. Any ideas on how I would go about achieving this?
Currently I have this code (and a bunch of others):
[[*recipeCalories:div=`2000`:mpy=`100`]]%
-
- 24,544 Posts
Try this:
Create a snippet called MyPercent with this code:
if (empty($m_val)) {
$m_val = 1;
}
if (!empty($output)) {
$output = (float)$output / (float)$m_val;
} else {
$output = 0;
} }
return (string) round((float)$output * 100 );
Use this tag:
[[*recipeCalories:MyPercent=`2000`]]%
-
- 932 Posts
Thanks Bob!
Haven't tried it yet, but really appreciate your replies as always.
-
- 932 Posts
Just to update this it's returning '0'. There was a syntax error of an additional curly brace but I removed this.
What I have is a MIGX value with a value of '279'
I'm calling this:
[[+nCalories:MyPercent=`2000`]]%
But it's just returning 0%. I think it should return 14%.
Any ideas?
Many thanks.
-
- 24,544 Posts
Initially, your tag was with a *. If you changed it because the code is in a Tpl chunk, the output modifier might not work in that case. You could try it uncached:
[[!+nCalories:MyPercent=`2000`]]%
I'm not sure it would work. If not, let me know and I'll give you a non-output-modifier method to try.
-
- 932 Posts
Quote from: BobRay at Jan 12, 2017, 07:57 AMInitially, your tag was with a *. If you changed it because the code is in a Tpl chunk, the output modifier might not work in that case. You could try it uncached:
[[!+nCalories:MyPercent=`2000`]]%
I'm not sure it would work. If not, let me know and I'll give you a non-output-modifier method to try.
Ahh ok. my bad.
I tried uncached but unfortunately still returning 0%.
Thank you, Bob.
discuss.answer
-
- 24,544 Posts
Try this:
/* MyPercent snippet code */
$m_val = $modx->getOption('m_val', $scriptProperties, '');
$value = $modx->getOption('value', $scriptProperties, '');
/* prevent division by 0 error */
if (empty($m_val)) {
$m_val = 1;
}
if (!empty($value)) {
$output = (float)$value / (float)$m_val;
} else {
$output = 0;
}
return (string)round((float)$output * 100);
Use this tag:
[[MyPercent? &value=`[[*recipeCalories]]` &m_val=`2000`]]%
or this, if it's in a Tpl chunk:
[[MyPercent? &value=`[[*recipeCalories]]` &m_val=`2000`]]%
Put the recipeCalories tag on the page alone to make sure it's not empty.
-
- 932 Posts
-
- 24,544 Posts
Glad I could help.