-3

I have String amount in a TextBox, which I want to divide by 100.

The value should round off to two decimal places. I tried and I am not getting a proper value.

Here is what I tried:

6766/100 = 67.66
47/100 = .47
98/100 = .98
Zapnologica
  • 22,170
  • 44
  • 158
  • 253
user3264676
  • 253
  • 5
  • 8
  • 20
  • 1
    It's doing an `int` calculation because both operands are ints. Try changing one of the numbers to a double by adding ".0", e.g. `6766/100.0` – Matthew Watson Mar 25 '14 at 10:03
  • http://stackoverflow.com/questions/22521867/float-doesnt-register-under-1/22521940#22521940 – heq Mar 25 '14 at 10:04
  • 1
    @MatthewWatson You should add a `d` for double, i.e. `0d`. – aevitas Mar 25 '14 at 10:04
  • 3
    @aevitas Why? Adding `.0` makes it a double too. – Matthew Watson Mar 25 '14 at 10:11
  • possible duplicate of [What's wrong with this division?](http://stackoverflow.com/questions/704702/whats-wrong-with-this-division) – Mark Rotteveel Mar 25 '14 at 10:42
  • possible duplicate of [How do you round a number to two decimal places in C#?](http://stackoverflow.com/questions/257005/how-do-you-round-a-number-to-two-decimal-places-in-c) – jww Mar 25 '14 at 10:55

4 Answers4

5

Use Math.Round. This example should get you going

string txtText = "78907";

double inputValue;

if (double.TryParse(txtText, out inputValue))
   double result = Math.Round(inputValue / 100, 2);

Output: 789.07

Ehsan
  • 31,833
  • 6
  • 56
  • 65
4

Use Math.Round, but one of both need to be a decimal type to avoid integer division:

double result = Math.Round(6766d / 100, 2);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

Use Math.Round. It has a parameter called precision.

Example:

Math.Round(1.23456, 2) -> 1.23
Andrius Naruševičius
  • 8,348
  • 7
  • 49
  • 78
0

Math.round will do.

Math.Round(1.23456, 2);

It will round input at 2 decimals

Roboneter
  • 867
  • 2
  • 13
  • 24