-3

The code something as below:

private double val1;
private int val2 =9;
private void displayValue()
{
        val1 = (val2/100);
    text1.Text = val1.ToString("0.000");
}

I am trying to display the val1 value (which actually should be 0.09) but I always get result "0.000" display in my text1. Someone please help me on how to convert this.

Sayse
  • 42,633
  • 14
  • 77
  • 146
NewBieS
  • 147
  • 2
  • 10
  • 2
    Because `9/100` performs [integer division](http://mathworld.wolfram.com/IntegerDivision.html) and result _always_ will be `0` not `0.9` not matter which type you assign it. This division always disregards fractional part. You could see watching `val1` if you debug your code. Change your integer division to floating point division. You can change your `val2` type from `int` to `double` for example. – Soner Gönül Oct 23 '15 at 06:59
  • try this: `val1.ToString("N2")` – Kamil Budziewski Oct 23 '15 at 07:00
  • `Val2/100d` should give you what you want – M.kazem Akhgary Oct 23 '15 at 07:00
  • refer here http://www.csharp-examples.net/string-format-double/ – Ramakrishna.p Oct 23 '15 at 07:04

2 Answers2

0
you need to convert your val2 to double:
private double val1;
private int val2 =9;
private void displayValue()
{
    val1 = ((double)val2/100);
    text1.Text = val1.ToString("0.000");
}

gives output as 0.0900

amit dayama
  • 3,246
  • 2
  • 17
  • 28
  • thanks you very much == i keep on searching the way to convert it and tried double(val2/100) but nvr do as you did ... haha – NewBieS Oct 23 '15 at 07:06
  • double(val2/100) it won't help. Because it will first divide val2 by 100 and give result as integer and then it converts to double. So you will get 0 as output in that case. or you may try val2/100.0 – amit dayama Oct 23 '15 at 07:07
0

It's because val2 is declared as an int. You can cast it before use:

(double)val2

Or declare as a double

double val2

I Hope this will help.