Calculating percentage of left over cost displaying result as NaN

francisthegod

Member
Joined
Jun 7, 2019
Messages
6
Programming Experience
1-3
C#:
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") + "%";

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 code works. Anyone have any idea how I can fix this please ? I have been trying for hours with no luck :( Thanks in advance
 
When dealing with numbers, they should be a numerical format. Lets say you have ::
C#:
            var i = "£150";

            var new_i = i.Replace("£", "");

            Console.WriteLine(new_i);
This outputs 150, thus removing the symbol at the start.

You can also use ::
C#:
            var i = "£150";

            var new_i = i.Substring(1);

            Console.WriteLine(new_i);
Which will also output 150.

You should be checking double try parse to see if it converted properly. Might I suggest glancing over the docs? Prevention is best, and its better to ensure your numbers are qualified integers. For fun, change try parse to parse and you will likely get a format exception, while try parse will just ignore it, thus execution of the console will give you the result you reported. Do you understand what you did wrong?

You should create a small function to check your numbers are in fact numbers and don't just blindly try parse.
 
As a quick aside, when dealing with money, don't use double or float. Use decimal instead. Although all three of the types are floating point type numbers, the latter was specifically designed to be more stable and not have the same amount of rounding issues as the former two types.

A good read:
What Every Computer Scientist Should Know About Floating-Point Arithmetic
 
Hi thanks for your replies I was able to fix problem by adding NumberStyles.Any, CultureInfo.GetCultureInfo("en-GB") to my TryParse.

I will give that article a read thanks.
 
Back
Top Bottom