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

B. Clay Shannon picture B. Clay Shannon · Sep 6, 2013 · Viewed 7.9k times · Source

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.

Answer

Greg Hewgill picture Greg Hewgill · Sep 6, 2013

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.