How to calculate a percentage

北慕城南 提交于 2019-12-13 09:53:48

问题


I want to calculate a percentage. My code is:

Bot.Log("[ KEYBOT ] The total is " + (suctrades * totaltrades ) / 100 + "% !");

If I do this, I only get 0. What am I doing wrong?


回答1:


Probably suctrades * totaltrades is still an int. The easiest way will be probably changing your code to:

((double)suctrades) * totaltrades/100

Or

suctrades * totaltrades/100.0

To force using double instead of int




回答2:


Try :

Bot.Log("[ KEYBOT ] The total is " + ((double)suctrades * totaltrades ) / 100 + "% !");

I assume suctrades and totaltrades are not of decimal type. This should fix this due to type propagation as expression is evaluated.




回答3:


Int is an integer type; dividing two ints performs an integer division, i.e. the fractional part is truncated since it can't be stored in the result type (also int!). Decimal, by contrast, has got a fractional part. By invoking Decimal.Divide, your int arguments get implicitly converted to Decimals.

You can enforce non-integer division on int arguments by explicitly casting at least one of the arguments to a floating-point type, e.g.: 100.0m this is casting to decimal !

decimal result = suctrades * totaltrades/100.0m


来源:https://stackoverflow.com/questions/27191908/how-to-calculate-a-percentage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!