I'm trying to convert the variable integer data into percentage in creating a bar chart. However it seems it is not working. What I missed?
string x1 = var_Product_name;
int y1 = Tools.ConvertToInt_02(var_Amount);
int y2 = Tools.ConvertToInt_02(var_Amount)/ 100.ToString("0.00%"); //This is the code I used to convert the var_Amount to get the percentage and display as data series in bar graph together with the var_Amount value however this isn't working
BarChartData_Product_Records_Data_View.Add(new BarChartSourceData_Product_Records_Data_View(x1, y1, y2));
CodePudding user response:
Most likely, var_Amount
is in the range 0..100, so even
100/100
results in 1, while smaller values, e.g.
25/100
results in 0 because y2
is an integer. To fix it, change y2
to a type that supports decimal portions such as float
, double
, or decimal
.
CodePudding user response:
First of all, if Tools.ConvertToInt_02(var_Amount)
returns a integer value this line not compile: you have int
value on before /
and string
value after /
.
You should see:
error CS0019: Operator '/' cannot be applied to operands of type 'int' and 'string'
If assuming that the var_Amount
is double
value that you need to convert to the percentage in string format, use the following method:
string specifier = "P";
var result = (var_Amount / 100).ToString(specifier, CultureInfo.CurrentCulture);
For example, if var_Amount
has value 12.3456
the result
will be 12.35 %
, when the current decimal point character for the current culture is .
.
For additional information see documentation: Double.ToString Method