15

I have a table column "Amount" of type money. When I am retrieving its value through a store procedure, it returns the value upto 4 decimal places(because of type money). I want the value upto two decimal places and I want it to handle in the code. How will I do it by rounding off the value to 2 decimal place. Thanks

Running Rabbit
  • 2,634
  • 15
  • 48
  • 69

8 Answers8

24

Read Custom Numeric Formats for detailed instructions on formatting numbers.

value.ToString("0.00");

In C# 6 or later, you can use string interpolation for a somewhat cleaner syntax.

$"{value:0.00}";
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 5
    +1. This one is better if you always want 2 decimal places even if value has only 1 say. This should be the accepted answer. – Mitch Wheat Mar 08 '13 at 06:40
5

Well, I tried it and got the correct result.

Below is the code that I used:

funding.amount= Math.Round(decimal.Parse(dr["Amount"].ToString()), 2).ToString();

//since the amount was of string type, therefore I used the above code. we can also use the below code:

decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);

http://msdn.microsoft.com/en-us/library/9s0xa85y.aspx

Running Rabbit
  • 2,634
  • 15
  • 48
  • 69
4

Format in presentation layer:

string.Format("{0:#.##}", value);
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
2
string.Format("{0:0.00}", your_value);
  • 2
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. Also the comment by @Md. Shafiqur Rahman links to the same solution – Hintham Oct 22 '18 at 07:23
1

You can use Standard Numeric Format Example:

decimal dValue = 1.268;
string sValue = dValue.ToString("N"); // 1.27
whastupduck
  • 1,156
  • 11
  • 25
1

In Leave Event write this code

 Double x;
        Double.TryParse(txtLocl.Text, out x);
        txtLocl.Text = x.ToString("0.00");

After leaving it allowed only two decimal places

sree aneev
  • 141
  • 4
  • 5
  • 18
0

test this code:

value.ToString("F2");
0
Text='<%#Bind("Value","{0:F2}") %>'
Code
  • 679
  • 5
  • 9