I needed to do some basic math ( X / Y =Z%) and I found the following code snippets on this forum:
add_shortcode('wpv-calculate', 'calculate_shortcode');
function calculate_shortcode($atts) {
return wpv_condition($atts);
}
[wpv-calculate evaluate=" [types field="current"][/types] / [types field="total"][/types] * 100 "]%
Everything works but now I need to limit the number of characters in the output (I really only want the final calculation to show up as something like 17.16%, but it's currently showing up as 17.157712305026%).
I've searched the forum for a solution but have come up empty-handed so far (I've given [trim length=][/trim] as well as length="" to no avail.).
I'm guessing that it may require a modification to the code added to the functions.php file but don't know what that might be (or even if that's the answer).
Any help would be greatly appreciated.
Hi dbarber,
Please try PHP function number_format, like this:
add_shortcode('wpv-calculate', 'calculate_shortcode');
function calculate_shortcode($atts) {
return number_format(wpv_condition($atts), 2);
}
More help:
hidden link
Hi Luoy
I added the snippet you provided to my functions.php file, updated it, refreshed one of the pages in question, and the site went blank on the front end.
I realized that I probably wasn't supposed to have both snippets of code in the functions.php file, so I deleted the original snippet (left the snippet you provided above), updated, refreshed, and the calculation was missing (no numbers, just the % sign).
So I decided to start again, with the original snippet, and then see if I could "stitch" a working solution together out of the original snippet and the snippet you provided.
So I replaced the snippet you provided with the original snippet, updated, refreshed, and got the following error message:
"Error while parsing the evaluate expression%"
Here's what that refers to:
[wpv-calculate evaluate=" [types field="detached-sales-current" output="raw" id="$market-updates"][/types] / [types field="detached-active-listings-current" output="raw" id="$market-updates"][/types] * 100 "]%
So I've got 2 problems. First, of course, is that the calculation is returning a parse error. And, second, after getting the first issue sorted, I'm not sure how to apply the snippet you provided.
Would you mind letting me know what I'm getting wrong / missing?
Many thanks
Dawson
Maybe it's just my iPad but it looks like some of the code snippet got cut off. Just in case, here it is again:
[wpv-calculate evaluate=" [types field="detached-sales-current" output="raw" id="$market-updates"][/types] / [types field="detached-active-listings-current" output="raw" id="$market-updates"][/types] * 100 "]%
Cheers
Disregard my follow up comments. Chrome was causing problems, so I cleared the cache, shut down, rebooted, used the snippet you provided, and everything is working as it should.
Many thanks!