Search code examples
c#mathcompact-frameworkwindows-ce.net-1.1

How can I show the decimal and two places after it when converting an int to double?


Given values such as 123, 1234, and 12345, I need these to be converted into, respectively, 1.23, 12.34, and 123.45

This code, when I enter 123, then 1234, then 12345 into textbox2:

int originalVal = Convert.ToInt16(textBox2.Text);
double doubled = Convert.ToDouble(originalVal/100);

...gives me 1, 12, and 123 instead of the expected 1.23, 12.34, and 123.45.

What do I need to do to get the desired result? Please note that this is a Windows CE / Compact Framework project using VS2003 and .NET 1.1.


Solution

  • You are doing integer division, because both originalVal and 100 are themselves integers. Try:

    originalVal/100.0
    

    The use of 100.0 makes the compiler generate code for a floating point division. Alternately, this would have the same effect:

    Convert.ToDouble(originalVal)/100
    

    where you are converting your originalVal integer to a double before doing the division.