Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating percentage of left over cost displaying result as NaN

Tags:

c#

wpf

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") + "%";  
like image 207
user8329959 Avatar asked Jan 26 '23 05:01

user8329959


1 Answers

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

like image 176
Dmitry Bychenko Avatar answered Jan 30 '23 09:01

Dmitry Bychenko