如何编写JSON公式实现(last_price-cost)/last_price*100计算?
JSON公式实现自定义计算值的问题
我想编写一个JSON公式来计算自定义值,目标公式是(last_price - cost) / last_price * 100,但搞不清计算的左右部分顺序,比如不知道该先执行*100还是/last_price操作。我写了一段JSON代码,觉得它实现的是(last_price-cost)*100的计算,代码如下:
"formula": { "operation": "*", "left": { "operation": "-", "left": { "operation": "value", "type": "custom_fields", "value": "last_price" }, "right": { "operation": "value", "type": "custom_fields", "value": "cost" } }, "right":{ "operation": "value", "type": "const", "field": 100 } }
你的判断没错,这段代码确实是计算(last_price - cost) * 100——最外层是乘法操作,左边是last_price减cost的结果,右边是常量100。
要实现目标公式(last_price - cost) / last_price * 100,先明确运算逻辑:数学里乘除属于同级运算,按从左到右的顺序执行,所以先算(last_price - cost)/last_price,再乘以100。对应的JSON结构需要调整层级,把除法放在乘法的左操作数位置:
"formula": { "operation": "*", "left": { "operation": "/", "left": { "operation": "-", "left": { "operation": "value", "type": "custom_fields", "value": "last_price" }, "right": { "operation": "value", "type": "custom_fields", "value": "cost" } }, "right": { "operation": "value", "type": "custom_fields", "value": "last_price" } }, "right": { "operation": "value", "type": "const", "field": 100 } }
这段代码的运算步骤是:
- 先计算最内层的
last_price - cost - 用上述结果除以
last_price - 最后将结果乘以100
完全匹配目标公式的逻辑。
另外提一句,虽然(last_price - cost)*100 / last_price和目标公式结果一致(乘除同级,顺序不影响最终数值),但按目标公式的书写顺序来编写JSON,语义上更清晰,不容易混淆。
内容的提问来源于stack exchange,提问作者Paul Jakov
相关产品推荐
相关产品推荐

