How to calculate a percentage

2019-09-27 01:33发布

问题:

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