Question

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.

Was it helpful?

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.

OTHER TIPS

double originalVal = Convert.ToDouble(textBox2.Text);
double doublePercented = originalVal/100D;

I see you already have your answer, but...

private TextBox txtNumerator, txtDenominator, txtResult;

public MyClass() {
  txtNumerator = new TextBox();
  txtNumerator.TextChanged += new TextChangedEvent(TextBox_TextChanged);
  txtDenominator = new TextBox();
  txtResult = new TextBox();
}

private void TextBox_TextChanged(object sender, EventArgs e) {
  double numerator = Convert.ToDouble(txtNumerator.Text.Trim());
  double denominator = Convert.ToDouble(txtDemominator.Text.Trim());
  if (denominator != 0) {
    double result = numerator / denominator;
    // Ref: http://www.csharp-examples.net/string-format-double/
    txtResult.Text = string.Format("{0:0.00}", result);
  } else {
    throw new DivideByZeroException("Denominator can not be zero.");
  }
}

You specifically asked how to get the double to 2 decimal places. String.Format will do that for you.

Also, using the event handlers, your people never have to click some calculate button.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top