0

I'm trying to declare a double in C# that has the value of a quotient. It doesn't seem to work...

double convert = 5 / 1024;

This keeps assigning the value 0 to the variable 'convert' instead of 0.0048828125.

I am using it in a serial read to convert the 10-bit integer back to a voltage...

static void Main(string[] args)
{
    double rawValue;
    double convert = 5 / 1024; // Assigns value of 0
    double convValue;
    string read;

    SerialPort sp = new SerialPort("COM3"); // Creates COM port 
    sp.BaudRate = 9600;
    sp.Open();

    for (;;)            
    {
        read = sp.ReadLine();
        rawValue = Convert.ToDouble(read);
        convValue = rawValue * convert;
        Console.WriteLine(Math.Round(convValue, 2));
    }
}

The serial read works fine; I can read and write to the console the 0-1023 number and then converter it manually. I just can't assign the conversion double with the expression "5 / 1024".

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
  • 1
    Possible duplicate of [Why does integer division in C# return an integer and not a float?](https://stackoverflow.com/questions/10851273/why-does-integer-division-in-c-sharp-return-an-integer-and-not-a-float) – Camilo Terevinto Jun 29 '18 at 21:53

2 Answers2

2

That (5 / 1024) is integer division. In integer division: the answer is zero. To tell it to use floating point: add a decimal point:

double convert = 5.0 / 1024;

Note it can also probably be declared const.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

Try inserting a "D" after the number, this way, the compiler can identify, with clarity, the desired type (in this case, the literal "D" represents the double type, just like "M" represents decimals).

Example:
double convert = 5d / 1024d;

Stacklysm
  • 233
  • 2
  • 11