How to calculate a percentage

2019-09-27 01:50发布

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?

3条回答
The star\"
2楼-- · 2019-09-27 02:00

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.

查看更多
Juvenile、少年°
3楼-- · 2019-09-27 02:04

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

查看更多
干净又极端
4楼-- · 2019-09-27 02:11

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
查看更多
登录 后发表回答