rewrite the wikitext {{#expr:({{{m 0}}})/(100-{{{y 0}}})}} *100}}%, so it does the same…
- User
rewrite the wikitext {{#expr:({{{m|0}}})/(100-{{{y|0}}})}} *100}}%, so it does the same math , but avoids a potential division by zero.
- Assistant
To avoid a potential division by zero, you can include a conditional check to ensure that the denominator is not zero. Here's how you can modify the wikitext to achieve this:
{{#ifexpr:(100-{{{y|0}}})=0|0|{{#expr:({{{m|0}}})/(100-{{{y|0}}})*100}}}}%This code checks if ( 100 - {{{y|0}}} ) equals 0. If it does, it returns 0 to avoid division by zero. Otherwise, it performs the original calculation.
- User
Myabe easier to do in Lua?
- Assistant
Yes, implementing this in Lua can be more straightforward and robust. You can create a Lua module for the math operation and include a check to avoid the division by zero. Here’s an example of how you can achieve this:
- First, create a new module (e.g.,
Module:SafeMath):
-- Module:SafeMath local p = {} function p.calculate(frame) local m = tonumber(frame.args.m) or 0 local y = tonumber(frame.args.y) or 0 local denominator = 100 - y if denominator == 0 then return "0%" else return string.format("%.2f%%", (m / denominator) * 100) end end return p- Then, use this module in your wikitext:
{{#invoke:SafeMath|calculate|m={{{m|0}}}|y={{{y|0}}}}}With this setup, you define a Lua module that performs the calculation while checking if the denominator is zero to prevent any division errors. The Lua function returns the result formatted as a percentage with two decimal places. If the division by zero would occur, it simply returns "0%".
- First, create a new module (e.g.,