Convert.ToDecimal calculation yields wrong precision

90 Views Asked by At

I'm trying to make a BMI Calculator (using meters and kilograms) in C#, but, when i type in 1.92m and 80Kg (or any other values), it gives me some weird results, like 0,0021701388888888888888888889.

namespace BMI
{
    internal class Program
    {
        static void Main(string[] args)
        {
            
            decimal height = Convert.ToDecimal(Console.ReadLine()); //1.92m
            decimal weight = Convert.ToDecimal(Console.ReadLine()); //80Kg
            decimal BMI = weight / (height*height);
            Console.WriteLine(BMI);// Result: 0,0021701388888888888888888889
        }
    }
}

Isn't it supposed to give me the value of 21.7013888889 without those zeros ? What am i doing wrong ? I am a complete beginner and i have no idea how to fix this.

2

There are 2 best solutions below

1
ENERGY.SERVICES On

Try to do it implicit like this. or Check what you're entering from console...

        string Height_Console = Console.ReadLine();
        decimal height = Convert.ToDecimal(Height_Console); //1.92m
        string Weight_Console = Console.ReadLine();
        decimal weight = Convert.ToDecimal(Weight_Console); //80Kg
        decimal BMI = weight / (height * height);
        Console.WriteLine(BMI);
        Console.ReadKey();

Check this link to get more information about data types DATA TYPES

1
quatnu On

It seems like the problem is in the decimal point. It may not recognize it correctly because some countries use "," and some use "." as the decimal. You can try inputting the height like this:

decimal height = Convert.ToDecimal(Console.ReadLine()) / 100; //192cm

If you don't like this solution, try inputting it with "," instead of "."