I am trying to show the percentage which is left after number1 has subtracted from number. The values I am calling contain a £ symbol and when running the code I get the result of NaN I guess this is to do with the £ sign as when removed the percentage shows. Anyone have any idea how I can fix this please ? I have been trying for hours with no luck :( Thanks in advance.
double number;
double number1;
double result;
double.TryParse(SelectedQuoteForEditing.JobPrice, out number);
double.TryParse(lblRate.Content.ToString().ToString(), out number1);
var left = Math.Round((number - number1) / number * 100, 2);
result = left;
ERGPerc.Content = result.ToString("P") + "%";
Well, double.NaN
is a result of 0.0 / 0.0
.
0.0 / 0.0 == double.NaN
that's why both number
and number1
are 0.0
. It means that
double.TryParse(SelectedQuoteForEditing.JobPrice, out number);
double.TryParse(lblRate.Content.ToString().ToString(), out number1);
either SelectedQuoteForEditing.JobPrice
is 0.0
or invalid (say, empty string) and the same for lblRate.Content.ToString().ToString()
.
Check the value double.TryParse
returns:
if (double.TryParse(SelectedQuoteForEditing.JobPrice, out number) &&
double.TryParse(lblRate.Content.ToString(), out number1) {
var left = Math.Round((number - number1) / number * 100, 2);
ERGPerc.Content = left.ToString("P") + "%";
}
else {
// at least one value is invalid
}
Edit: If you want to parse currency, say GB
ones (see £150.00
in the comments), you have to let the system know about it:
double.TryParse(SelectedQuoteForEditing.JobPrice,
NumberStyles.Any, // allow currency symbols
CultureInfo.GetCultureInfo("en-GB"), // which currency? GB
out number);
double.TryParse(lblRate.Content.ToString(),
NumberStyles.Any, // allow currency symbols
CultureInfo.GetCultureInfo("en-GB"), // which currency? GB
out number1);
otherwise the Parse
fails (what £
means? It doesn't correct part of floating point value!) you'll get 0.0
for number
and number1
and double.NaN
on (number - number1) / number
execution
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With